简体   繁体   English

C ++赋值与删除的赋值运算符一起工作吗?

[英]C++ assignment works with deleted assignment operator?

I have a piece of code that looks something like this: 我有一段代码看起来像这样:

class B
{
private:
    const A& obj;
    size_t val;

    // private - prohibited
    B& operator=(const B& other);

public:
    B(const A& obj_): obj(obj_)
    {
        val = 0;
    }
};

class C
{
    void func()
    {
        A a1;
        B b1(a1);
        B b2 = b1; // should throw error?
    }
}

Class B has a private assignment operator. Class B有一个私有的赋值运算符。 Nonetheless assignment in C::func() compiles without errors. 尽管如此, C::func()赋值C::func()编译而不会出错。 But how? 但是如何?

B b2 = b1 does not use the assignment operator, because it's not assignment , it's copy initialization - using constructor, not assignment operator. B b2 = b1不使用赋值运算符,因为它不是赋值 ,而是复制初始化 -使用构造函数,而不是赋值运算符。

See also copy initialization 另请参阅复制初始化

That's the copy constructor getting called, not the assignment operator. 那是拷贝构造函数被调用,而不是赋值运算符。

The reason being is that when you initialize a variable, a constructor (in this case, the copy constructor) gets called. 原因是在初始化变量时,将调用构造函数(在本例中为复制构造函数)。

B b2 = b1; // construction

This is different from assignment 这与作业不同

b2 = b1; // b2 is already declared, so assignment

To stop this behavior, just delete your copy constructor. 若要停止此行为,只需删除您的副本构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM