Error declaring a class with std :: vector structures containing std :: unique_ptr

Despite working with C # for several years, doing things in C ++ is sometimes difficult. I completely embrace the use of smart pointers, but now I come across the following puzzle

I have a Foo structure like

 struct Foo { Foo(std::unique_ptr<Bar> bar) : m_myBar(std::move(bar)) {} private: std::unique_ptr<Bar> m_myBar; }; 

In another class, I want to have a vector containing instances of Foo, but the next line

  std::vector<Foo> m_Foos; 

gives compilation errors saying that the copy constructor has been deleted. The SO thread “ Why can't I push push_back_in_ptr into a vector? ” Gives an explanation as well as a fix. However, the question is about the vector of unique pointers, whereas I have a vector of structures containing a unique pointer. The proposed solution is to use displacement semantics, but how is this applicable in my situation? Or should I do something else?

+5
source share
2 answers

As you say, m_Foos is actually a data member of another class (I will call it FooHolder ). If you have not provided a copy constructor for FooHolder , the compiler will automatically generate it. This copy constructor will invoke the copy constructors of all FooHolder data FooHolder , including m_Foos . Of course, the copy constructor std::vector<Foo> contains a compilation error, since Foo not copied. This is probably why you get the error.

You will need to provide an appropriate copy constructor for FooHolder if you can and want this class to be copied. Otherwise, you can simply declare the move constructor (possibly the default), which will remove the copy constructor:

 struct FooHolder { FooHolder(FooHolder&&) = default; private: std::vector<Foo> m_Foos; }; 
+4
source

You cannot copy unique pointers. You can only move them:

 Foo(std::unique_ptr<Bar> bar) : m_myBar(std::move(bar)) {} // ^^^^^^^^^^^^^^ 
+1
source

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


All Articles