Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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?

Still, using placement new in for copying is evil. Plays really bad with inheritance, esp. when there are virtual bases. Deduplicator Jun 6, 2014 at 23:34 @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 6, 2014 at 23:38 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 6, 2014 at 23:49

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);