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

后端 未结 3 583
耶瑟儿~
耶瑟儿~ 2020-12-20 09:40

How do we ususaly deal with a vector whose elements are pointers to object? My specific question is the comment at the end of the code supplied below. Thanks.



        
相关标签:
3条回答
  • 2020-12-20 09:47

    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!

    0 讨论(0)
  • 2020-12-20 09:55

    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.

    0 讨论(0)
  • 2020-12-20 10:12

    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.

    0 讨论(0)
提交回复
热议问题