Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

c++ - Does shallow copy call member objects' constructors?

Assuming i have this code:

class A {
public:
    int x;
    A(){}
    A(const A& a){} //copy constructor
    operator= (const A &a){...}
};
class B {
public:
    A a;
    B(){}
};
int main() {
    B b;
    B c = b; //shallow copy
    B d;
    d = b; //shallow assignment
}

Will the shallow copyassignment call member A a's copy constructorassignment operator overloading? Or shortly does shallow copy perform member objects' user-made copy constructor & assignment operator or a shallow one as well?

question from:https://stackoverflow.com/questions/65905010/does-shallow-copy-call-member-objects-constructors

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Then the answer is yes, the copy constructor will be called, but the assignment operator will not.

The copy constructor will be called because the defaulted copy constructor is called, but the assignment operator is not. The defaulted assignment operator will call the defaulted copy constructor, and the defaulted copy constructor will call the copy constructor of the base class, but the defaulted assignment operator is not called.

The reason is simple: the defaulted assignment operator is not called because the defaulted assignment operator is declared "A& operator=(const A& a)".

The above is a case in which the calling convention (the "= default" is a member function calling convention) is used.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...