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

后端 未结 6 1925
你的背包
你的背包 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 10:57

    In your example, the vector is created when the object is created, and it is destroyed when the object is destroyed. This is exactly the behavior you get when making the vector a normal member of the class.

    Also, in your current approach, you will run into problems when making copies of your object. By default, a pointer would result in a flat copy, meaning all copies of the object would share the same vector. This is the reason why, if you manually manage resources, you usually need The Big Three.

    A vector of pointers is useful in cases of polymorphic objects, but there are alternatives you should consider:

    1. If the vector owns the objects (that means their lifetime is bounded by that of the vector), you could use a boost::ptr_vector.
    2. If the objects are not owned by the vector, you could either use a vector of boost::shared_ptr, or a vector of boost::ref.

提交回复
热议问题