Reputation: 3585
Was reading more about smart pointers and came across the concept of constructor getting deleted when you copy one unique_ptr to another. What exactly is that concept?
#include<iostream>
#include<memory>
class Person {
public:
int e;
Person(int e) : e(e) { }
};
int main() {
std::unique_ptr<Person> p (new Person(5));
// Below line seems to be deleting constructor and thus error in compiling.
std::unique_ptr<Person> q = p;
}
std::move semantics are working fine though.
Upvotes: 3
Views: 11947
Reputation: 1
copy construtor and copy assignment operator are deleted. So, unique pointer can't copy and assign to other object.
Upvotes: 0
Reputation: 1150
The unique_ptr
class:
The class satisfies the requirements of MoveConstructible and MoveAssignable, but of neither CopyConstructible nor CopyAssignable.
The copy constructor and copy assignment operator do not work in the case of unique_ptr. The unique_ptr holds the ownership exclusively. It cannot be shared.
https://en.cppreference.com/w/cpp/memory/unique_ptr
Upvotes: 0
Reputation: 8589
Normal copy semantics will result in both q
and p
holding a pointer to the same Person
object and both their destructors will then delete
the same object.
That's invalid. You should delete the same allocation exactly once.
Move semantics however are permitted to modify the object being copied. In the case of std::unique_ptr<>
the object is set to "empty" (i.e. assigned nullptr
).
Upvotes: 1
Reputation: 3638
Since a unique pointer should be unique, it cannot be copied. It can only be moved.
Hence, the copy constructor is deleted.
Upvotes: 10