为什么引用unique_ptr会以这种方式运行?

Adr*_*n17 3 c++ reference unique-ptr

vector<int> v1, v2;

/*1*/        vector<int> &someReference=v1;     //compiles
/*2*/        someReference=v2;         //compiles

vector<unique_ptr<int>> vec1, vec2;

/*3*/        vector<unique_ptr<int>> &otherReference=vec1;    //compiles
/*4*/        otherReference=vec2;     //ERROR
Run Code Online (Sandbox Code Playgroud)

我理解如果第3行和第4行都没有编译,但第三行不会导致任何编译错误 - 显然第一次初始化引用并传递它没有问题; 问题只有在我第二次尝试分配时才会出现.

我无法理解幕后发生的事情使得第二次任务变得不可能.

ava*_*kar 6

这与引用无关,它是unique_ptr无法复制的.

unique_ptr<int> p1, p2;
p1 = p2; // error
Run Code Online (Sandbox Code Playgroud)

因此,unique_ptr也不能复制矢量.

vector<unique_ptr<int>> vec1, vec2;
vec1 = vec2; // error
Run Code Online (Sandbox Code Playgroud)

  • @Adrian17对,引用是其他东西的别名,它总是绑定到那个东西.你不能改变它的别名. (2认同)