简体   繁体   中英

Why copy constructor is not called here?

For the following code :

    #include<iostream>
    using namespace std;

    class Test
    {
    public:
       Test(const Test &t) { cout<<"Copy constructor called"<<endl;}
       Test()        { cout<<"Constructor called"<<endl;}
    };

    Test fun()
    {
        cout << "fun() Called\n";
        Test t;
        return t;
    }

    int main()
    {
        Test t1;
        Test t2 = fun();
        return 0;
    }

I am really confused regarding when the copy constructor is called ? Like if I am running the above program copy constructor is not called. That means if I am messing up with the parameters passed to the copy constructor (eliminating const keyword) it shouldn't show any compiler error. But its showing

"no matching function for call to 'Test::Test(Test)' "

Moreover, the fun() is returning an object of type test , which is created during fun() execution. Why the copy constructor is not called here ?

    int main()
    {
        fun();
        return 0;
    }

also if I am making following changes to main function why copy constructor is called only once , not twice ?

    int main()
    {
        Test t2 = fun();
        Test t3 = t2;
        return 0;
    }

It is because copy initialization is used here, not copy constructor, due to the NRVO enabled in your compiler. You should specify

-fno-elide-constructors

flag on gcc

The C++ standard allows an implementation to omit creating a temporary which is only used to initialize another object of the same type. Specifying this option disables that optimization, and forces G++ to call the copy constructor in all cases.

or compile it with cl /Od program.cpp on VS (/O1 and /O2 enables NRVO )

C++ : Avoiding copy with the “return” statement

When I run your code in VS2010, I get the right result:

1.

Constructor called
fun() Called
Constructor called
Copy constructor called

2.

fun() Called
Constructor called
Copy constructor called

3.

fun() Called
Constructor called
Copy constructor called
Copy constructor called

The copy constructor has been called correctly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM