为什么以下代码也会调用复制构造函数?

3 c++ copy-constructor move-semantics copy-elision nrvo

为什么g_Fun()执行return temp它会调用复制构造函数?

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;
}
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 7

因为您按值返回,但请注意,由于RVO,不需要调用复制构造函数.

根据优化级别,可能会也可能不会调用复制程序 - 不要依赖它们.