Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the meaning for &t for expression new (&t) T(t) in c++?

Tags:

c++

what is the meaning for &t for expression new (&t) T(t) in c++?

as titled.

T t;
new (&t) T(t);
like image 699
jiafu Avatar asked Jan 07 '14 05:01

jiafu


2 Answers

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();
like image 189
JaredPar Avatar answered Sep 23 '22 11:09

JaredPar


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.

like image 37
rullof Avatar answered Sep 25 '22 11:09

rullof