6

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?

Community
  • 1
  • 1
Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359
  • same thing as before : have you tried ? – BatchyX Jan 21 '11 at 21:22
  • @BatchyX - nope. It's quite a lot of refactoring in my case, so I rather ask. Besides, if the answer isn't on StackOverflow, it should be :) – Jonathan Livni Jan 21 '11 at 21:29
  • Been there, done that. But I have learned from it, in most case you can write 20-30 line test programs that will verify/invalidate an idea in less than 5 minutes. `struct test { ~test() { std::cout << "~test" << std::endl; } }; int main() { vector > v; v.push_back( make_shared() ); }` (or something in this line, its hard to write code in a comment). Then compile and verify whether destructors are called or not. Try again with `scoped_ptr` and see if the code even compiles. Throw in a couple other operations (`resize`, ...) and verify. – David Rodríguez - dribeas Jan 22 '11 at 00:32
  • You guys are right. I should really develop this habit :) Even if I do, I guess I'll still ask the same questions on StackOverflow, because I like the interaction here. The answers are never boolean, I always learn the wider context. For instance, in this case I actually found that scoped_ptr cannot be used in containers before I submitted the question, but I submitted it nonetheless and Billy ONeal referred me to the pointer containers which I wasn't aware of and now I'll go read about them... – Jonathan Livni Jan 22 '11 at 09:05

1 Answers1

20

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.

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552