unique_ptr 中的构造函数被删除

Hem*_*ava 1 c++ unique-ptr

正在阅读有关智能指针的更多信息,并遇到了当您将一个 unique_ptr 复制到另一个时构造函数被删除的概念。这个概念到底是什么?

#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;
}
Run Code Online (Sandbox Code Playgroud)

不过 std::move 语义工作正常。

drR*_*rtz 7

由于唯一指针应该是唯一的,因此它不能被复制。它只能被移动。

因此,复制构造函数被删除。