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