Home >Backend Development >C++ >Why does pushing a `unique_ptr` into a `vector` require `std::move`?
Understanding the Error
Consider the following program:
#include <memory> #include <vector> int main() { std::vector<std::unique_ptr<int>> vec; int x(1); std::unique_ptr<int> ptr2x(&x); vec.push_back(ptr2x); // Error occurs here }
This seemingly innocuous code attempts to push a unique_ptr into a vector. However, the compilation fails with an error:
error: deleted function 'std::unique_ptr<int>::unique_ptr(const std::unique_ptr<int>&)'
The Nature of unique_ptr
The unique_ptr is a fundamental part of the C Standard Library that is used to manage the lifetime of dynamically allocated objects. It ensures that the pointer it encapsulates cannot be copied. This means the ownership of the managed object is exclusive to the unique_ptr container.
The Issue
The error arises because the program attempts to push a copy of the unique_ptr into the vector. However, as mentioned earlier, unique_ptrs cannot be copied. Instead, they can only be moved.
Solution
Therefore, to fix the issue, we need to use the std::move function to transfer ownership of the unique_ptr from the original variable to the vector. The corrected code should look like this:
#include <memory> #include <vector> int main() { std::vector<std::unique_ptr<int>> vec; int x(1); std::unique_ptr<int> ptr2x(&x); vec.push_back(std::move(ptr2x)); // Use std::move to transfer ownership }
Now, the compiler will be able to successfully compile and execute the program without any errors.
Additional Considerations
It is important to note that the use of unique_ptr in the code is incorrect. unique_ptr is meant to manage dynamically allocated objects. The pointer in the code is pointing to a local variable that will be destroyed when the function returns. To fix this, the code should allocate the object dynamically:
#include <memory> #include <vector> int main() { std::vector<std::unique_ptr<int>> vec; std::unique_ptr<int> ptr(new int(1)); // Dynamically allocate the object vec.push_back(std::move(ptr)); }
Alternatively, you can use the std::make_unique function to create the unique_ptr and allocate the object in one line:
#include <memory> #include <vector> int main() { std::vector<std::unique_ptr<int>> vec; vec.push_back(std::make_unique<int>(1)); }
The above is the detailed content of Why does pushing a `unique_ptr` into a `vector` require `std::move`?. For more information, please follow other related articles on the PHP Chinese website!