Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What constructor or operator is used in a return (C++)

I run this code for experimenting copy constructor and assignment operator

class AClass {

    private:
        int a;

    public:
        AClass (int a_) : a(a_) {  
            cout << " constructor AClass(int) " << a << endl;
        }

        AClass(const AClass & x) : a(x.a) { 
            cout << " copy constructor AClass(const AClass &) " << a << endl;
        }

        AClass & operator=(const AClass & x) { 
                a = x.a;
                cout << " AClass& operator=(const AClass &) " << a - endl;
                return *this;
        }
};

AClass g () {
    AClass x(8);
    return x;
}

int main () {

    cout << " before AClass b = g() " << endl;
    AClass b = g();
    cout << " after" << endl;

    cout << " before AClass c(g()) " << endl;
    AClass c  (g());
    cout << " after" << endl;
}

and found that no message appears for the return x; Why? Should not the copy constructor or operator= be called?

This is the output:

 before AClass b = g() 
 constructor AClass(int) 8
 after

 before AClass c(g()) 
 constructor AClass(int) 8
 after
like image 860
cibercitizen1 Avatar asked Dec 04 '22 22:12

cibercitizen1


1 Answers

The compiler is allowed to elide copying in a case like this. This is called Return Value Optimization.

like image 118
Fred Larson Avatar answered Jan 04 '23 22:01

Fred Larson