Is it safe to push_back 'dynamically allocated object' to vector?

前端 未结 4 766
长发绾君心
长发绾君心 2020-12-17 01:07

Whenever I need to add dynamically allocated object into a vector I\'ve been doing that the following way:

class Foo { ... };

vector v;

v.push_         


        
4条回答
  •  一个人的身影
    2020-12-17 01:54

    The preferred way to do this is to use a container of smart pointers, for example, a std::vector > or a std::vector > (shared_ptr can be found in Boost and C++ TR1 as well; std::unique_ptr is effectively restricted to C++0x).

    Another option is to use a container that owns dynamic objects, like those containers provided by the Boost Pointer Containers library.

提交回复
热议问题