Home > Backend Development > C++ > Why Can't I Directly Push Unique Pointers into Vectors?

Why Can't I Directly Push Unique Pointers into Vectors?

Susan Sarandon
Release: 2024-12-25 02:15:13
Original
846 people have browsed it

Why Can't I Directly Push Unique Pointers into Vectors?

Trouble with Pushing Unique Pointers into Vectors

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
Copy after login

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));
Copy after login

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));
Copy after login

In C 14, we can further simplify this using make_unique:

make_unique<int>(5);
Copy after login

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!

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