In attempting to manipulate unique pointers within a vector, programmers may encounter difficulties. This article aims to explain why this issue arises and provide a solution.
Consider the following code snippet:
std::vector<std::unique_ptr<int>> vec; int x(1); std::unique_ptr<int> ptr2x(&x); vec.push_back(ptr2x); // Error: Can't copy a unique_ptr
This code generates an error due to the underlying principles of unique pointers. A unique pointer ensures that only a single container controls the managed pointer. Hence, copying or creating multiple unique pointers to the same object is forbidden.
To resolve this issue, we must employ the move constructor, which transfers ownership of the pointer from one unique pointer to another. Here's the corrected code:
vec.push_back(std::move(ptr2x));
It's crucial to note that using unique pointers to manage pointers to local variables, such as x in the provided example, is incorrect. Local variables are automatically managed, and their lifetime ends when the containing block completes. Instead, allocate objects dynamically:
std::unique_ptr<int> ptr(new int(1));
In C 14, we can further simplify this using make_unique:
make_unique<int>(5);
The above is the detailed content of Why Can't I Directly Push Unique Pointers into Vectors?. For more information, please follow other related articles on the PHP Chinese website!