0

I am learning cpp, and now have a problem. Here are the code and the result.

What I very want to know are why there is only one constructor between "1" and "2" and why there are assignment and constructor between "3" and "4".

Thank you in advance

the result

#include <iostream>
#include <string>
using namespace std;

class A{
public:
    A(){
        cout << "Empty-constructor" << endl;
    }
    A(const A &a){
        cout << "Copy-constructor" << endl;
        this->v = a.v;
    }
    A operator=(const A &a){
        cout << "Assignment" << endl;
        this->v = a.v;
        return *this;
    }
    int get(){
        return v;
    }
    void set(int v){
        this->v = v;
    }
private:
    int v;
};

A func(){
    A a;
    return a;
}

int main(){
    cout << "1" << endl;
    A b = func();
    cout << "2" << endl;
    A c;
    cout << "3" << endl;
    c = b;
    cout << "4" << endl;
    return 0;
}
Community
  • 1
  • 1
bob
  • 13
  • 1

1 Answers1

4

A b = func(); only produces construction due to copy elision/NRVO; the new A is constructed directly into the caller's memory.

b = c; involves both assignment and construction because you wrote your assignment operator incorrectly, having it return by value, rather than by reference, so after the assignment is performed, it copy-constructs from the object you've just assigned to, returning the copy (which isn't used, and gets thrown away immediately). That's a giant waste, and should really be fixed to make the assignment operator return by reference, changing:

A operator=(const A &a){

to:

A& operator=(const A &a){

Even better, use the copy-and-swap idiom to avoid duplicating code for copying/swapping all over the place.

ShadowRanger
  • 108,619
  • 9
  • 124
  • 184
  • @user4581301: Thanks. I decided on linking the copy-and-swap idiom question rather than the basic rules and idioms for operator overloading, since the assignment operator specifically gets rather short shrift in the basic rules and idioms question. – ShadowRanger Nov 24 '18 at 05:31
  • Agreed. A better targeted choice. – user4581301 Nov 24 '18 at 05:36