Search code examples
c++unique-ptr

Constructor deleted in unique_ptr


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.


Solution

  • Since a unique pointer should be unique, it cannot be copied. It can only be moved.

    Hence, the copy constructor is deleted.