Home > Backend Development > C++ > How to Implement Copy Constructors for Classes with `unique_ptr` Members in C 11?

How to Implement Copy Constructors for Classes with `unique_ptr` Members in C 11?

Barbara Streisand
Release: 2024-12-03 10:54:17
Original
139 people have browsed it

How to Implement Copy Constructors for Classes with `unique_ptr` Members in C  11?

Implementing Copy Constructors for Classes with unique_ptr Members

When working with classes that utilize a unique_ptr member variable, implementing a copy constructor becomes crucial. In this article, we will delve into the techniques for creating copy constructors in C 11 for such classes.

As unique_ptr cannot be shared, it's imperative to either deeply copy its contents or convert it to a shared_ptr. The following example demonstrates deep copying:

class A
{
   std::unique_ptr<int> up_;

public:
   A(int i) : up_(new int(i)) {}
   A(const A&amp; a) : up_(new int(*a.up_)) {}
};
Copy after login

In this approach, a new unique_ptr is allocated and assigned a copy of the original pointer's content.

Alternatively, one can utilize a move constructor instead of a copy constructor:

A(A&&amp; a) : up_(std::move(a.up_)) {}
Copy after login

However, this method introduces different semantics, as it transfers ownership of the unique_ptr from the source to the target object.

For completeness, the full set of assignment operators would be:

A&amp; operator=(const A&a)
{
   up_.reset(new int(*a.up_));
   return *this;
}

A&amp; operator=(A&&amp; a)
{
   up_ = std::move(a.up_);
   return *this;
}
Copy after login

Deciding whether to use copy or move constructors depends on the context. If the class is intended to be used in a std::vector, the choice between making the class move-only or copyable is influenced by whether the vector should be the sole owner of the objects.

The above is the detailed content of How to Implement Copy Constructors for Classes with `unique_ptr` Members in C 11?. 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