Reputation: 7867
I searched some post about delete this in c++,and know that delete this is usually a bad idea,because delete this usually means poor management : the number of new and delete is not match, also it may have some pointers outside the class still point to this.
But the post I searched mostly about just deleting the original object, doesn't discuss the case of replacing the original object with new object.
sometimes I want to recreate the object,because I want the object to go back to initial state, by "realloc" the object using delete this+memmove(this,new A(),sizeof(A)) like this:
class A{
public:
int value;
void test(){
delete this;
memmove(this,new A(),sizeof(A));
}
};
is it safe? or is there any undefined behaviour?
also if even it works,is it a bad coding style?
Upvotes: 2
Views: 149
Reputation: 171147
This code is heavily in UndefinedBehaviour-land. delete this
does more than call the destructor—it deallocates the memory as well. The memmove
thus copies into unallocated memory.
Furthermore, it has a memory leak, since the pointer returned from new A()
is immediately forgotten.
I believe you intended to do this:
void test()
{
this->~A();
new (this) A();
}
This calls the destructor on this
, and then the default constructor in the space pointed to by this
.
The real questions is why do that, though. It's rather intricate low-level management. In my opinion, it would be better to give a proper assignment operator to the class and do this:
void test()
{
*this = A();
}
Remember, the easier it is to understand what code does, the better the code generally is.
Upvotes: 4
Reputation: 12999
You can call delete this
- the self-destruction mechanisms used in some reference counting implementations work this way BUT you may not refer to this
ever again at all because the results are undefined.
If you want to restore the same object to an initial state then can't you provide private cleanup()
and init()
methods that do the work?
Upvotes: 0
Reputation: 838
delete this deallocate the memory. So the memmove writes in a dangling pointer which is undefined behavior.
I don't know what you are trying to do, but did you try move constructors introduced in c++11?
Upvotes: 0