Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is this syntax - new (this) T(); [duplicate]

Tags:

c++

I run into such C++ code:

T& T::operator=(const T&t) 
{
   ...
   new (this) T(t);
   ...
}

This line looks so foreign to me:new (this) T(t);

I can see it is calling the copy constructor to populate "this", but somehow I just cannot make sense out of the syntax. Guess I am so used to this = new T(t);

Could you help me out?

like image 724
my_question Avatar asked Oct 25 '25 04:10

my_question


1 Answers

It is so-called the new placement operator. it constructs an object at address specified by the expression in parentheses. For example the copy assignment operator can be defined the following way

const C& C::operator=( const C& other) {
   if ( this != &other ) {
      this->~C(); // lifetime of *this ends
      new (this) C(other); // new object of type C created
   }
   return *this;
}

In this example at first the current object is destroyed using an explicit call of the destructor and then at this address a new object is created using the copy constructor.

That is this new operator does not allocate a new extent of memory. It uses the memory that was already allocated.

This example is taken from the C++ Standard. As for me I would not return a const object. It would be more correctly to declare the operator as

C& C::operator=( const C& other);
like image 65
Vlad from Moscow Avatar answered Oct 26 '25 16:10

Vlad from Moscow