0

What does (ptr) stands for and why does it change the data stored in ptr?

struct X
{
    int a;
    int const b;
};
    
X* ptr = new X{ 1, 2 };
X* nptr = new (ptr) X{ 3, 4 };

And for some reason it doesn't run in any godbolt's compilers but does in visual studio

kirjosieppo
  • 617
  • 3
  • 16
  • Seems like the author of this code was trying to reinvent the assignment-operator in the most dangerous way possible (short of `memcpy()`, anyway :) ) – Jeremy Friesner Feb 01 '23 at 06:23
  • Read about [placement new](https://stackoverflow.com/a/222578/12002570) and also refer to [Two different values at the same memory address](https://stackoverflow.com/questions/3593687/two-different-values-at-the-same-memory-address) – Jason Feb 01 '23 at 06:27

1 Answers1

1

It requires #include <new> to work. It is an overloaded new operator which calls the constructor without allocating new memory. Instead, the new struct is constructed to memory pointed by ptr and the old data is thus overwritten. See that for reference.

kirjosieppo
  • 617
  • 3
  • 16