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

后端 未结 6 1908
你的背包
你的背包 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:54

    A pointer to a vector is very rarely useful - a vector is cheap to construct and destruct.

    For elements in the vector, there's no correct answer. How often does the vector change? How much does it cost to copy-construct the elements in the vector? Do other containers have references or pointers to the vector elements?

    As a rule of thumb, I'd go with no pointers until you see or measure that the copying of your classes is expensive. And of course the case you mentioned, where you store various subclasses of a base class in the vector, will require pointers.

    A reference counting smart pointer like boost::shared_ptr will likely be the best choice if your design would otherwise require you to use pointers as vector elements.

提交回复
热议问题