There is a class MyClass, of course with a constructor, you need to create a vector of smart pointers to objects of this class. The pointer itself is created, but when trying to add to the vector an error occurs. What did I miss?

#include <memory> #include <vector> using namespace std; Int main() { vector<unique_ptr<MyClass>> vectorPtr; unique_ptr<MyClass> p1(new MyClass); // до этого момента всё в порядке vectorPtr.push_back(p1); return 0; } 

    1 answer 1

    std::unique_ptr does not have a copy constructor, so to put it into a vector, you need to move it there:

     vectorPtr.push_back(std::move(p1)); 

    Or so:

     vectorPtr.push_back(std::make_unique<MyClass>()) 

    Or create directly in the vector:

     vectorPtr.emplace_back(new MyClass);