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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With