c++ - is delete this + memmove(this,new A(),sizeof(A)) safe and is it a bad idea? -
i searched post delete in c++,and know delete bad idea,because delete means poor management : number of new , delete not match, may have pointers outside class still point this.
but post searched deleting original object, doesn't discuss case of replacing original object new object.
sometimes want recreate object,because want object go initial state, "realloc" object using delete this+memmove(this,new a(),sizeof(a)) this:
class a{ public: int value; void test(){ delete this; memmove(this,new a(),sizeof(a)); } }; is safe? or there undefined behaviour?
also if works,is bad coding style?
this code heavily in undefinedbehaviour-land. delete this more call destructor—it deallocates memory well. memmove copies unallocated memory.
furthermore, has memory leak, since pointer returned new a() forgotten.
i believe intended this:
void test() { this->~a(); new (this) a(); } this calls destructor on this, , default constructor in space pointed this.
the real questions why that, though. it's rather intricate low-level management. in opinion, better give proper assignment operator class , this:
void test() { *this = a(); } remember, easier understand code does, better code is.
Comments
Post a Comment