Relationship between assignment operator and user-defined constructor

北城以北 提交于 2019-12-02 06:05:00

问题


#include <iostream>

class A{
};

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

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

This outputs

constructor
constructor

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?


回答1:


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;

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.



来源:https://stackoverflow.com/questions/46651284/relationship-between-assignment-operator-and-user-defined-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!