Unique Pointers and Copy Constructors
Why does the compiler generate an error when I try to define a copy constructor for a class containing a unique_ptr member?
When a class contains a unique_ptr member, the compiler-generated copy constructor is deleted because unique_ptr is not copyable. The purpose of unique_ptr is to ensure exclusive ownership of the pointed-to resource, so it cannot be copied.
To define a copy constructor for a class with a unique_ptr member, you need to manually implement the copying behavior. This typically involves creating a new unique_ptr in the destination object and copying the pointed-to resource.
Here's an example:
#include <memory>
class MyClass {
public:
MyClass(const MyClass& other)
: ptr{std::make_unique<int>(*other.ptr)} {}
private:
std::unique_ptr<int> ptr;
};In the copy constructor, we create a new unique_ptr and initialize it with a copy of the value pointed to by other.ptr. This ensures that the destination object has its own independent copy of the resource.
By manually implementing the copy constructor this way, you can define the appropriate copying behavior for your class while still maintaining the exclusive ownership semantics of unique_ptr.
Copy Semantics and Return Value Optimization
Learn how to control exactly how our objects get copied, and take advantage of copy elision and return value optimization (RVO)