Home >Backend Development >C++ >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& a) : up_(new int(*a.up_)) {} };
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&& a) : up_(std::move(a.up_)) {}
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& operator=(const A&a) { up_.reset(new int(*a.up_)); return *this; } A& operator=(A&& a) { up_ = std::move(a.up_); return *this; }
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!