13

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?
  • 2
    google placement new. – jfly Mar 24 '14 at 08:47
  • 2
    http://stackoverflow.com/questions/222557/what-uses-are-there-for-placement-new – Ben Mar 24 '14 at 08:47
  • 1
    possible duplicate of [Can I use placement new(this) in operator=?](http://stackoverflow.com/questions/7177884/can-i-use-placement-newthis-in-operator) – Oliver Charlesworth Mar 24 '14 at 08:49
  • 4
    you haven't found it because that's the documentation for the new *operator*, and not for the expression: http://en.cppreference.com/w/cpp/language/new – Karoly Horvath Mar 24 '14 at 08:50
  • 4
    I don't think this question should be closed. It might be helpful for people to find an answer to my question *if they do not know about placement new* -- which they likely wouldn't if they had this question. Also, the question asks why it would be used in this situation. Thus, it is different than the possible duplicated flagged above. –  Mar 24 '14 at 09:01

1 Answers1

17

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)

jalf
  • 243,077
  • 51
  • 345
  • 550
  • 5
    It's noteworthy that if the construction fails (throws an exception), the memory at `*this` will not contain a valid object, and future attempts to use the object (including any destructor call if the object goes out of scope or is `delete`d) will have Undefined Behaviour. – Tony Delroy Mar 24 '14 at 08:50
  • Also noteworthy, in a derived class (if the class does not prohibit derivation) the placement new in assignment operator may set up a vtable pointer to the wrong class, again with Undefined Behavior. – Cheers and hth. - Alf Mar 24 '14 at 09:08
  • 1
    @jalf: re "what you're looking at is a copy constructor which" should be "what you're looking at is a copy assignment operator which". – Cheers and hth. - Alf Mar 24 '14 at 09:11
  • @Cheersandhth.-Alf gah, yeah, you're right of course! Thanks for pointing that out. – jalf Mar 24 '14 at 18:03
  • And also noteworthy, nothing prevents you from calling this operator with an argument that has automatic storage. Which is a recipe for desaster. – Damon Mar 24 '14 at 18:13