Home > Backend Development > C++ > How Can I Correctly Push a `std::unique_ptr` into a `std::vector`?

How Can I Correctly Push a `std::unique_ptr` into a `std::vector`?

Linda Hamilton
Release: 2024-12-28 13:07:16
Original
479 people have browsed it

How Can I Correctly Push a `std::unique_ptr` into a `std::vector`?

Unable to Push Back Unique_Ptr into a Vector

The provided code attempts to push a std::unique_ptr into a vector, which results in a compilation error due to the inability of performing a copy operation on the unique pointer.

Recall that std::unique_ptr ensures exclusive ownership of the contained pointer to a specific object. This means that when assigning a unique pointer, the ownership is moved and not copied. Consequently, making copies of a unique pointer is prohibited as multiple owners would violate its unique ownership guarantee.

To resolve the issue and push the unique pointer into the vector correctly, use the std::move function as follows:

vec.push_back(std::move(ptr2x));
Copy after login

std::move transfers the ownership of the unique pointer to the vector, enabling its insertion into the vector without violating the unique ownership rule.

It's crucial to note that the initial usage of std::unique_ptr in this code is incorrect. It attempts to manage a pointer to a local variable, which contradicts the required control over the object's lifetime. To prevent this discrepancy, allocate the object dynamically using, for instance:

std::unique_ptr<int> ptr(new int(1));
Copy after login

The above is the detailed content of How Can I Correctly Push a `std::unique_ptr` into a `std::vector`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template