Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this copy constructor elision?

The following code doesn't call the copy constructor.

struct X
{
   int x;
   X(int num)
   {
      x = num;
      std::cout << "ctor" << std::endl;
   }
   X(const X& other)
   {
      std::cout << "copy ctor" << std::endl;
   }
};

int main(int argc, _TCHAR* argv[])
{
   X* x = new X(3);
   X* y(x);
}

Output:

ctor

Is it copy-ctor elision?

like image 287
AMCoder Avatar asked May 23 '26 07:05

AMCoder


1 Answers

The code

X* x = new X(3);
X* y(x);

is not the same as

X x(3);
X* y = new X(x);

You're not copying objects, but pointers. After X* y(x);, both pointers will point to the same object.

like image 153
Luchian Grigore Avatar answered May 24 '26 21:05

Luchian Grigore