3

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?

my_question
  • 3,075
  • 2
  • 27
  • 44
  • 6
    [Placement new](http://en.cppreference.com/w/cpp/language/new). `this` is not an lvalue, so `this = new T(t);` doesn't compile. – chris Jun 06 '14 at 23:21
  • 2
    Still, using placement new in for copying is evil. Plays really bad with inheritance, esp. when there are virtual bases. – Deduplicator Jun 06 '14 at 23:34
  • 1
    @chris IIRC `this = new T(t);` is *really* old syntax for placement-new. -- edit: yes, up to Release 2.0 of CFront, D&E pp. 91-92 -- 2.0 was released in 1989, so this syntax is **older than 25 years** o.O – dyp Jun 06 '14 at 23:38
  • @Deduplicator See [GotW #23](http://www.gotw.ca/gotw/023.htm) – dyp Jun 06 '14 at 23:46
  • 1
    Oh, didn't realize `T` was the class itself and not a template parameter. In that case, @my_question, definitely look into the copy-swap idiom. – chris Jun 06 '14 at 23:49
  • 1
    @dyp Well, I know that's not the only reason it's a bad idea. – Deduplicator Jun 06 '14 at 23:53

1 Answers1

7

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);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335