【问题标题】:Relationship between assignment operator and user-defined constructor赋值运算符与自定义构造函数的关系
【发布时间】:2017-10-09 16:45:25
【问题描述】:
#include <iostream>

class A{
};

class B: public A{
public:
    B(A&& inA){
        std::cout<<"constructor"<<std::endl;
    }
};

int main(){
    B whatever{A{}};
    whatever=A{};
}

这个输出

constructor
constructor

至少使用 C++14 标准和 GCC。如何定义赋值运算符可以导致调用构造函数而不是operator=?赋值运算符的这个属性有名字吗?

【问题讨论】:

    标签: c++ assignment-operator


    【解决方案1】:

    自从你遇到了所有conditions for generating a move-assignment operator。编译器为你合成的move-assignment operator是这样的:

    B& operator=(B&&) = default;
    

    回想一下,临时对象可以绑定到const左值引用右值引用。通过Implicit Conversion Sequences,您的临时A{} 将转换为用于进行移动分配的临时B。您可以使用 explicit 构造函数禁用此功能。

    【讨论】:

    • “你的临时 A{} 被转换为临时 B” - 你能引用草稿吗?我只能在您链接的页面中找到提到派生到基础的转换。
    • @EuriPinhollow,这与“派生到基(B-&gt;A)”转换无关,并且在OP的sn-p中没有这样的上下文...... OP的代码有Converting Constructor[class.conv.ctor] 将右值传递给A 的对象,即:B(A&amp;&amp;)。这意味着A 的任何rvalue 对象都可以转换为BUser-defined Conversion Sequences[over.ics.user] 考虑了从“作为参数传递的类型”到“预期类型”的所有可能的隐式转换方法
    • 请将其编辑为答案,我接受它。这部分是最重要的。
    猜你喜欢
    • 1970-01-01
    • 2013-09-28
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 1970-01-01
    • 2011-07-19
    • 2017-10-06
    相关资源
    最近更新 更多