奇怪的C ++构造函数/复制构造函数问题在g ++ [英] weird C++ constructor/copy constructor issues in g++
问题描述
#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;
}
此代码也调用复制构造函数。为什么这个工作?我记得第一次我跑这个程序,它seg故障。但过了一会儿,它开始调用这个副本的缺点。现在工作! Wierd。
但如果我替换fun()如下:
X fun(){
X s;
return s;
}
不被调用。我以为复印的缺点。在这种情况下将被调用。但正如@ flyfishr64所指出的,RVO正在这里发挥作用。但是它仍然不解释我返回一个引用的情况。
任何解释?要扩展@ 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.
这篇关于奇怪的C ++构造函数/复制构造函数问题在g ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!