Jonathan Livni
Jonathan Livni

Reputation: 107092

Can boost::smart_ptr be used in std containers?

Can boost::smart_ptr such as scoped_ptr and shared_ptr be used in std containers such as std::map?

class SomeClass
{
    std::map<int,boost::scoped_ptr<SomeOtherClass> > a_map;
};

As boost::smart_ptr can be used for polymorphism, is it true in this case as well? Will the destruction of the container, trigger the correct destruction of the subclasses?

Upvotes: 6

Views: 2700

Answers (1)

Billy ONeal
Billy ONeal

Reputation: 106549

scoped_ptr cannot be used in standard containers because it cannot be copied (which is required by the containers' interfaces). shared_ptr may be used, however.

If you can't use C++11 and you're using boost already, consider the pointer containers which will perform somewhat better than a container of shared pointers.

If you're using C++11, consider a container of unique_ptr, which should perform similarly to boost's pointer containers.

Upvotes: 20

Related Questions