Boost logo

Boost :

Subject: Re: [boost] [ptr_container] ptr_map + abstract class = error
From: Václav Haisman (v.haisman_at_[hidden])
Date: 2009-03-22 05:57:36


Ross Levine wrote, On 21.3.2009 23:25:
> The following code does not compile in VS2008:
>
>
> #include <boost/ptr_container/ptr_map.hpp>
>
> class A
> {
> public:
> virtual void is() = 0;
> };
>
> class B : public A
> {
> public:
> virtual void is() {}
> };
>
> int main()
> {
> boost::ptr_map<int, A> c;
> int i = 1;
> c.insert(i, new B);
> A& my_ref = c[1]; // error: cannot instantiate abstract class
> }
>
>
> It seems that using operator[] creates a new A for an unmatched key,
> which creates an abstract instance. Using the find method works fine.
> Should this be documented? The example in the documentation uses
> operator[] on an ABC, and thus shouldn't compile either.
This is well known behaviour which is "documented" by the standard:

23.3.1.2 map element access [lib.map.access]
T& operator[](const key_type& x);
1 Returns: (*((insert(make_pair(x, T()))).first)).second.

The ptr_map<> just mimicks the behaviour. It has to, what would the
operator[] return otherwise?

--
VH

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk