当 private unique_ptr 涉及 class 定义时 C++ 中的引用初始化

Reference initialization in C++ when private unique_ptr is involved in class definition

下面的编译错误是怎么解释的?

#include <iostream>
#include <memory>
#include <vector>

using namespace std;

class A{
    unique_ptr<vector<short>> v;
public:
    A(){
        v = unique_ptr<vector<short>>(new vector<short>());
        cout << "A()" << endl;
    }
    A(const A& a) : A(){
        cout << "A(const A& a)" << endl;
    }
};

int main() {

    A a1; // prints A()
    A a2 = a1; // prints A() then A(const A& a)
    A& a3 = a1; // prints nothing
    a3 = a1; // compile time error: use of deleted function ‘A& A::operator=(const A&)

    return 0;
}

其实,为什么A& a3 = a1可以,而a3 = a1不行呢?另外,正在使用哪个重载版本的 operator= 以及如何正确实施它以避免此类问题?

行中

a3 = a1;

您正在调用已删除的 operator=(请记住 unique_ptr 是不可复制的)。 g++ 为你吐出错误:

error: use of deleted function 'A& A::operator=(const A&)'

而在行中

A& a3 = a1; 

没有复制,你只初始化了一个引用。

您可能想移动指针,例如

a3 = std::move(a1); 

不幸的是,它不起作用,因为您显式声明了一个复制构造函数,这会阻止编译器生成默认的移动构造函数和赋值运算符。解决方案:将移动赋值运算符和移动构造函数声明为=default;

A& operator=(A&&) = default;
A(A&&) = default;

上面的行 a3 = std::move(a1) 将起作用。