Why does the following code also call the copy constructor?

Why g_Fun()

is return temp

it called by the copy constructor when executed in ?

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;
}

      

+3


source to share


2 answers


Since you are returning by value, but note that no call to the copy constructor is required, due to the RVO .



Depending on the level of optimization, copy-ctor may or may not be called - don't rely on either.

+7


source


The copy constructor can be called whenever we return an object (and not its reference), because a copy of it must be created, which is done by the default copy constructor.



CExample g_Fun()
{
 return CExample(0);    //to avoid the copy constructor call
 }

      

0


source







All Articles