bob
bob

Reputation: 13

About constructor and assignment operator in C++

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;
}

Upvotes: 0

Views: 56

Answers (1)

ShadowRanger
ShadowRanger

Reputation: 155373

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.

Upvotes: 4

Related Questions