vector of pointer to object - how to avoid memory leak?

◇◆丶佛笑我妖孽 提交于 2019-11-29 12:54:42

Yes, you have to do that to avoid memory leak. The better ways to do that are to make a vector of shared pointers (boost, C++TR1, C++0x, )

 std::vector<std::tr1::shared_ptr<A> > l;

or vector of unique pointers (C++0x) if the objects are not actually shared between this container and something else

 std::vector<std::unique_ptr<A>> l;

or use boost pointer containers

  boost::ptr_vector<A> l;

PS: Don't forget A's virtual destructor, as per @Neil Butterworth!

Use an array of shared_ptr, or similar smart pointer. And note that your base class must have a virtual destructor for this code to work correctly.

The best way would be to use smart pointers (Boost shared_ptr) to avoid this kind of things. But if you NEED to have raw pointers I believe this is the way to do it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!