且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

奇怪的C ++构造函数/复制构造函数问题在g ++

更新时间:2022-12-13 22:29:45

任何解释?要扩展@ flyfishr64的答案



此处调用复制构造函数,因为:

  X s = fun(); 

是初始化。你使用fun()来构造对象,而不是调用默认的构造函数。它等价于:

  X s(fun()); 

您看到的缺点是针对fun()中的实例。请参阅这篇文章: C ++中的赋值运算符 。更多。


#include <iostream>
using namespace std;

class X {
        public:
                X() {
                        cout<<"Cons"<<endl;
                }
                X(const X& x){
                        cout<<"Copy"<<endl;
                }
                void operator=(const X& x){
                        cout<<"Assignment called";
                }
};

X& fun() {
        X s;
        return s;
}

int main(){
        X s = fun();
        return 0;
}

This code calls the copy constructor also. Why does this work? I recall that the first time I ran this program, it seg faulted. But after a while, it started calling this copy cons. and now works!! Wierd.

But if I replace, fun() as follows:

X fun() {
        X s;
        return s;
}

Then copy cons. is not called. I thought that the copy cons. would be called in this case. But as pointed out by @flyfishr64, RVO is coming into play here. But it still does not explain the case where I am returning a reference. I think it should always segfault.

Any explanations?

To expand on @flyfishr64's answer

The copy constructor is invoked here because this:

X s = fun();

is an initialization. You are using fun() to construct the object, not invoking the default constructor. It is equivalent to:

X s(fun());

The "Cons" you see printed out is for the instance in fun(). See this article: Assignment operator in C++ for more.