Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ 'new' operator - Modes of use?

I recently ran into an unusual use of the new operator to re-initialise a C++ class, the code is as follows:

#include <iostream>
struct Test { Test() { std::cout<<"Test Ctor\n"; }  };
int main()
{
  Test t ;
  new (&t) Test;
  return 0 ;
}

If this code is run, the Test ctor is called twice. In this case it appears that the 'new' operator is using the pointer to the object as the source of the memory rather than allocating new memory, valgrind comfirms no memory leaks.

Can someone shed some light on this use of the 'new' operator?

like image 890
Gearoid Murphy Avatar asked Sep 17 '25 03:09

Gearoid Murphy


1 Answers

This operator is called placement new. It runs the constructor of the object at the given addresss without prior memory allocation. It could be used when allocating a large array first, then constructing many object on it, for instance.

like image 68
qdii Avatar answered Sep 19 '25 19:09

qdii