为什么按赋值初始化需要复制构造函数,如果它不使用它

时间:2015-10-25 09:55:48

标签: c++

请考虑以下代码:

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);行在定义时不使用复制构造函数,为什么它在删除时会尝试使用它?

1 个答案:

答案 0 :(得分:6)

问题在于您的main:行

X x = X(5);

copy initialization - 它看起来像一个赋值运算符,但它被替换为引擎盖下的复制构造函数。

如下重写代码可以解决问题,因为它不会让编译器选择避免使用赋值运算符:

X x1(3);
X x2(5);
x1 = x2;

Demo.

相关问题