Should I use std :: unique_ptr <T> in the std :: vector member variable in my class?

Imagine a class C that has a m_MyList member m_MyList type std::vector in which I want to store objects of type MyClass . C has two functions that add or remove objects in m_MyList . m_MyList should also be accessible to C users, as they must read the collection of MyClass objects. An external collection reader will not be able to modify the collection, so MyClass objects belong only to C

Now my question is: In C ++ 11 style, what is the best T to store in a vector? The following options are possible:

  • std::vector<MyClass>
  • std::vector<MyClass*>
  • std::vector<unique_ptr<MyClass>> using std:move to push unique_ptr on vector
+6
source share
2 answers

If MyClass objects belong to C , the best option would be the simplest:

 std::vector<MyClass> 

The only reason I could use std::unique_ptrs here is if you need to save pointers to the base class for polymorphism. In this case, unique_ptrs are used to allocate resources when the vector is destroyed. But then the C interface should not transfer ownership to clients.

+13
source

Raw pointers ( std::vector<MyClass*> ) are invalid if C owns objects. The other two are pretty similar with the following tradeoffs:

  • std::vector<MyClass> - requires that MyClass be available for copying and / or moving
  • std::vector<unique_ptr<MyClass>> - requires (additional) dynamic allocations

The type of operations performed on the container may also be relevant. To take an extreme example, if MyClass is large and the container is repeatedly shuffled, unique_ptr would be a better choice.

+11
source

Source: https://habr.com/ru/post/917079/


All Articles