No, a std::unique_ptr cannot be copied. The design of std::unique_ptr enforces unique ownership of the object it manages, meaning that only one unique_ptr can own a particular resource at any given time.
If you attempt to copy a unique_ptr, it will result in a compilation error. However, you can transfer ownership of the managed object from one unique_ptr to another using std::move(). This effectively "moves" the resource, leaving the original unique_ptr in a null state.
Here’s an example demonstrating this:
#include <iostream>
#include <memory>
class MyClass {
public:
MyClass() {
std::cout << "MyClass constructor called." << std::endl;
}
~MyClass() {
std::cout << "MyClass destructor called." << std::endl;
}
};
int main() {
std::unique_ptr<MyClass> ptr1 = std::make_unique<MyClass>();
// Attempting to copy will result in a compilation error
// std::unique_ptr<MyClass> ptr2 = ptr1; // Error: cannot copy unique_ptr
// Correct way to transfer ownership
std::unique_ptr<MyClass> ptr2 = std::move(ptr1); // ptr1 is now null
return 0; // MyClass destructor will be called when ptr2 goes out of scope
}
In this example, ptr1 is moved to ptr2, transferring ownership of the MyClass instance. After the move, ptr1 becomes null.
