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 the Placement Syntax
; This statment:
new (&t) T(t);
Constructs an object at the adress of t
(&t
) but it doesn't allocate memory.
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