Is it valid to directly call a (virtual) destructor?

China☆狼群 提交于 2019-11-29 13:44:20

Calling a destructor manually is a perfectly valid thing, regardless of if it's virtual. You just want to make sure that it's just called once for every constructor call.

Is it undefined behaviour to use the object after such a destructor call? 

Yes.

What if one immediatly reinitializes it with a new (this) MyClass(); call?

Still horrifically undefined.

Do not manually destruct an object unless you had to manually place it, e.g. with placement new or some equivalent, and definitely do not ever re-initialize a destructed object like that and hope to avoid UB. Classes like std::vector very explicitly make accessing destroyed objects UB, and it remains UB even if you then make a new element in it's place.

An example of valid use involving one and only one construction:

typedef boost::aligned_storage<
    sizeof(T), boost::alignement_of<T>::value>::type arena_type;
arena_type arena;
T* p = new (&arena) T();
p->~T();
// Don't touch p now

This can be useful when e.g. implementing a variant type (warning: exception-safety left as an exercise to the reader). C++0x unrestricted unions will have similar uses for class types.

Note that for a class type, the above would be UB if you did not call the destructor.

As long as you are calling placement new on top of your pre-allocated chunk of POD memory, its perfectly valid to deallocate invoking any destructor, virtual or not.

placement new and explicit deallocator invocation will just invoke the constructor and destructor in the referenced areas, so memory allocation is effectively factored out of the object lifecycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!