Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

c++ - 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
";
        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;
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...