赋值运算符和用户定义的构造函数之间的关系 [英] Relationship between assignment operator and user-defined constructor

查看:83
本文介绍了赋值运算符和用户定义的构造函数之间的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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=?赋值运算符的此属性有名称吗?

at least with C++14 standard and GCC. How is it defined that assignment operator can result in call to constructor instead of operator=? Is there a name for this property of assignment operator?

推荐答案

由于您满足生成移动分配运算符的所有条件.编译器为您合成的 move-assignment运算符的形式为:

Since you meet all the conditions for generating a move-assignment operator. The move-assignment operator the compiler synthesizes for you is in the form of:

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

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

Recall that temporaries can be bound to const lvalue references and rvalue references. By Implicit Conversion Sequences, your temporary A{} is converted to a temporary B which is used to make the move assignment. You may disable this with explicit constructors.

这篇关于赋值运算符和用户定义的构造函数之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆