+ 3

Can any one help me to understand below code?

char* ptr = new char[sizeof(T)]; // allocate memory T* tptr = new(ptr) T; // construct in allocated storage ("place") tptr->~T(); // destruct delete[] ptr; // deallocate memory

12th Dec 2017, 4:22 PM
$Ā¢šŽā‚¹š”­!šØš“
$Ā¢šŽā‚¹š”­!šØš“ - avatar
3 Answers
+ 9
Yes it works, but new(&mem[number... it's not safe. I think you should use something like [ sizeof(base)*index] instead of a number.. you won't know the size of an object, because if you want to add functionalities to your class later, you can have serious troubles.
14th Dec 2017, 8:26 AM
AZTECCO
AZTECCO - avatar
+ 7
it is tricky! T * tptr = new(ptr) T doesn't allocate memory, it constructs the T obj at the given pointer (ptr). the ptr pointer have been allocated previously whit the correct size.. new char[sizeof(T)] now the tricky part is that ptr is a pointer of type char[] ,it holds an array of chars. the size of memory allocated is T size but it cannot hold a T class type.. so the T * tptr is a new pointer that holds a T type and contains the same address that ptr contains. the difference is between the address of tptr and the address of pre. tptr==ptr but &ptr != &tptr hope it helps and tell me if you need a better explain
12th Dec 2017, 8:10 PM
AZTECCO
AZTECCO - avatar
0
hey @AZTECCO is this placement new operator. I have used it as below. Is it? https://code.sololearn.com/cl2LB21ckOnM/?ref=app
13th Dec 2017, 3:11 AM
$Ā¢šŽā‚¹š”­!šØš“
$Ā¢šŽā‚¹š”­!šØš“ - avatar