what is the meaning for &t for expression new (&t) T(t) in c++?
as titled.
T t;
new (&t) T(t);
This is referred to as the 'placement new' syntax. The T
value is constructed in the address that is specified by &t
.
This sample is a bit off since it's creating a new T in the exact location of an existing T using the copy constructor. I think it's easier to explain this concept with an explicit address. Here is a variation of this code.
T t;
void* pAddress = malloc(sizeof(T));
new (pAddress) T(t);
// Or just creating a T without a copy ctor
new (pAddress) T();
This is an example of placement new, where the container is the starting address of the object t
created with the Type T
The example code creates an Object of Type T
using the copy constructor which accepts a parameter of Type T
and places the object in the memory location of the object t
.
Just to conceive the Idea, consider the Type as an integer, so your template code would look like
int t;
new (&t) int(t);
So apparently, the placement new is redundant and confusing. The only reason for writing such an odd code may be is to force the initialization of an object using Copy Constructor which might have some additional code apart from copying the contents of the object which user might be interested.
This is the Placement Syntax
; This statment:
new (&t) T(t);
Constructs an object at the adress of t
(&t
) but it doesn't allocate memory.