Pointer to vector vs vector of pointers vs pointer to vector of pointers

后端 未结 6 1924
你的背包
你的背包 2021-02-03 10:33

Just wondering what you think is the best practice regarding vectors in C++.

If I have a class containing a vector member variable. When should this vector be declared a

6条回答
  •  天涯浪人
    2021-02-03 11:04

    Deleting all elements in a vector manually is an anti-pattern and violates the RAII idiom in C++. So if you have to store pointers to objects in a vector, better use a 'smart pointer' (for example boost::shared_ptr) to facilitate resource destructions. boost::shared_ptr for example calls delete automatically when the last reference to an object is destroyed.

    There is also no need to allocate MyClass::my_vector using new. A simple solution would be:

    class MyClass {
    
       std::vector m_vector;
    };
    

    Assuming whatever is a smart pointer type, there is no extra work to be done. That's it, all resources are automatically destroyed when the lifetime of a MyClass instance ends.

    In many cases you can even use a plain std::vector - that's when the objects in the vector are safe to copy.

提交回复
热议问题