Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does new (this) mean?

Tags:

c++

I found this code sample for study:

T & T::operator=(T const & x)
{
  if (this != &x)
  {
    this->~T(); // destroy in place
    new (this) T(x); // construct in place
  }
  return *this;
}

When I look at the documentation for new there is no version that takes a pointer. Thus:

  1. What does new (this) mean?
  2. What is it used for?
  3. How can it be called like this if it is not listed in the documentation?
like image 490
Walt Dizzy Records Avatar asked Mar 24 '14 08:03

Walt Dizzy Records


1 Answers

It is called "placement new", and the comments in your code snippet pretty much explain it:

It constructs an object of type T without allocating memory for it, in the address specified in the parentheses.

So what you're looking at is a copy assignment operator which first destroys the object being copied to (without freeing the memory), and then constructs a new one in the same memory address. (It is also a pretty bad idea to implement the operator in this manner, as pointed out in the comments)

like image 194
jalf Avatar answered Oct 22 '22 07:10

jalf