Placing a new equivalent of behavior

I have a question about placing syntax newin C ++. Are the following two code fragments functionally equivalent and can be used interchangeably (I do not mean that the second should be used when the first is suitable)?

# 1

T* myObj = new T();
// Do something with myObj
delete myObj;

# 2

char* mem = new char[sizeof(T)];
T* myObj = new (mem) T();
// Do something with myObj
myObj->~T();
delete[] mem;

Is there something I should be especially careful about when I use the new layout syntax as follows?

+5
source share
5 answers

They are not equivalent because they have different behavior if the constructor or destructor Tthrows.

new T() , , . char* mem = new char[sizeof(T)]; T* myObj = new (mem) T(); ( -, , ). , delete myObj , , ~T().

T* myObj = new T();/*other code*/delete myObj; :

//When using new/delete, T::operator new/delete
//will be used if it exists.
//I don't know how do emulate this in
//a generic way, so this code just uses
//the global versions of operator new and delete.
void *mem = ::operator new(sizeof(T));
T* myObj;
try {
    myObj = new (mem) T();
}
catch(...) {
    ::operator delete(mem);
    throw;
}
/*other code*/
try {
    myObj->~T();
    ::operator delete(mem);
}
catch(...) {
    //yes there are a lot of duplicate ::operator deletes
    //This is what I get for not using RAII ):
    ::operator delete(mem);
    throw;
}
+11

, :

void *mem = operator new(sizeof(T));
T *myobj = new(mem) T();

// ...

myobj->~T();
operator delete(mem);

, ::operator new , 'operator new, , new char [], .

: , . @Mankarse (), .

+8

: .. , , () .

, , , .

, , , placement new. , placement new , , T ( 25% ). placement new, , .

0

, T. . , , . .

0

. , , , , "mem", , , "myObj."

, , # 1 . # 2 , "mem", - .

- "mem". , ?

myObj ( , , Mankarse), № 1, № 2.

So, be careful to manage "mem" correctly. One general approach is as follows:

template<class T> void destroy(T* p, Arena& a)
{
        if (p) {
                p->~T();        // explicit destructor call
                a.deallocate(p);
        }
}
0
source

All Articles