考虑以下代码:
class X {
int a;
public:
X(int a) : a(a){std::cout<<"in constructor";}
// X(const X& x) : a(x.a){std::cout<<"in copy constructor";}
X(const X& x) = delete;
X& operator=(const X& x) {
std::cout<<"in assignment";
a = x.a;
return *this;
}
};
int main(int argc, char *argv[]) {
X x = X(5);// error: `use of deleted function`
return 0;
}
这给出了一个错误:use of deleted function
。但是,如果我取消注释复制构造函数并删除 delete
行,它工作正常,但不使用复制构造函数(输出为:in constructor
)。
那么如果 X x = X(5);
行在定义的时候没有使用拷贝构造函数,为什么在删除的时候尝试使用它呢?
最佳答案
问题出在您的 main
: 行
X x = X(5);
是copy initialization - 它看起来像一个赋值运算符,但在底层被复制构造函数取代。
按如下方式重写代码可以解决问题,因为它不会让编译器选择避免使用赋值运算符:
X x1(3);
X x2(5);
x1 = x2;
关于c++ - 如果不使用赋值初始化为什么需要复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33328369/