Copying Classes with Unique Pointers in C 11
Creating a copy constructor for a class containing a unique_ptr, a smart pointer that enforces exclusive ownership, poses unique challenges. In C 11, managing unique_ptr members requires careful consideration.
Solution:
To implement a copy constructor, you have two options:
class A { std::unique_ptr<int> up_; public: A(int i) : up_(new int(i)) {} A(const A& a) : up_(new int(*a.up_)) {} };
std::shared_ptr<int> sp = std::make_shared<int>(*up_);
Additional Considerations:
A(A&& a) : up_(std::move(a.up_)) {}
A& operator=(const A& a) { up_.reset(new int(*a.up_)); return *this; } A& operator=(A&& a) { up_ = std::move(a.up_); return *this; }
The above is the detailed content of How to Properly Copy C 11 Classes Containing `unique_ptr` Members?. For more information, please follow other related articles on the PHP Chinese website!