为什么g_Fun()
执行到return temp
时会调用copy constructor?
class CExample
{
private:
int a;
public:
CExample(int b)
{
a = b;
}
CExample(const CExample& C)
{
a = C.a;
cout<<"copy"<<endl;
}
void Show ()
{
cout<<a<<endl;
}
};
CExample g_Fun()
{
CExample temp(0);
return temp;
}
int main()
{
g_Fun();
return 0;
}
最佳答案
因为您按值返回,但请注意不需要调用复制构造函数,因为 RVO .
根据优化级别,copy-ctor 可能会或可能不会被调用 - 不要依赖任何一个。
关于c++ - 为什么下面的代码也会调用拷贝构造函数呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14509463/