Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy Constructor is not invoked [duplicate]

Possible Duplicate:
Why copy constructor is not called in this case?

Consider the sample program below:

#include <iostream>

using namespace std;

class sample
{
    private:
        int x;

    public:
        sample(int a=0) : x(a)
        {
            cout << "default ctor invoked\n";
        }

        sample(const sample& obj)
        {
            cout << "copy ctor invoked\n";
        }

};

int main()
{
    sample s2 = sample(20); //Line1
    sample s3 = 20; //Line2

    return 0;
}

In Line1, first the constructor of sample class is invoked explicitly with the argument 20. Then i expected the copy constructor to be invoked to initialize s2.

In Line2, first the constructor of sample class is invoked implicitly first with the argument 20. Here also i expected the copy constructor to be invoked to initialize s2.

In both cases, the copy constructor is not invoked? Why is this happening? I believe, there is something wrong with my understanding of the invocation of copy constructor. Could someone correct me where i am going wrong?

like image 240
nitin_cherian Avatar asked Jan 10 '12 04:01

nitin_cherian


1 Answers

This is expected. It's called copy elision.

Your expectation is correct, but they made an exception in C++ (for performance) which allows the compiler to treat your expression as direct initialization of one instance while bypassing the copy constructor.

like image 118
justin Avatar answered Sep 28 '22 08:09

justin