为什么不在这里调用复制构造函数? [英] Why copy constructor is not called here?
问题描述
以下代码:
#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;
}
我真的很困惑,当调用复制构造函数时?喜欢如果我运行上面的程序,拷贝构造函数不会被调用。这意味着如果我搞砸了参数传递给复制构造函数(消除const关键字),它不应该显示任何编译器错误。但它显示
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
没有匹配的函数调用'Test :: Test(Test)'
"no matching function for call to 'Test::Test(Test)' "
此外,fun()返回一个类型为test的对象,它是在fun()执行期间创建的。为什么不在这里调用复制构造函数?
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;
}
推荐答案
此处使用的不是复制构造函数,因为您的编译器中启用了 NRVO 。您应该指定
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
在gcc上标记
C ++标准允许实现省略创建一个临时的
,它只用于初始化同一类型的另一个对象。
指定此选项禁用该优化,并强制G ++到
在所有情况下调用复制构造函数。
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.
或者在VS(/ O1和/ O2 cl / Od program.cpp library / 8f8h5cxt.aspxrel =nofollow>启用NRVO )
or compile it with cl /Od program.cpp
on VS (/O1 and /O2 enables NRVO)
这篇关于为什么不在这里调用复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!