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

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

    Usually solution 1 is what you want since it’s the simplest in C++: you don’t have to take care of managing the memory, C++ does all that for you (for example you wouldn’t need to provide any destructor then).

    There are specific cases where this doesn’t work (most notably when working with polymorphous objects) but in general this is the only good way.

    Even when working with polymorphous objects or when you need heap allocated objects (for whatever reason) raw pointers are almost never a good idea. Instead, use a smart pointer or container of smart pointers. Modern C++ compilers provide shared_ptr from the upcoming C++ standard. If you’re using a compiler that doesn’t yet have that, you can use the implementation from Boost.

提交回复
热议问题