[ptr_container] ptr_map + abstract class = error

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.

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

Ross Levine skrev:
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.
Ok, the docs needs to be corrected then. Thanks -Thorsten
participants (3)
-
Ross Levine
-
Thorsten Ottosen
-
Václav Haisman