Is it allowed to delete this;
if the delete-statement is the last statement that will be executed on that instance of the class? Of course I\'m sure that the ob
If it scares you, there's a perfectly legal hack:
void myclass::delete_me()
{
std::unique_ptr bye_bye(this);
}
I think delete this
is idiomatic C++ though, and I only present this as a curiosity.
There is a case where this construct is actually useful - you can delete the object after throwing an exception that needs member data from the object. The object remains valid until after the throw takes place.
void myclass::throw_error()
{
std::unique_ptr bye_bye(this);
throw std::runtime_exception(this->error_msg);
}
Note: if you're using a compiler older than C++11 you can use std::auto_ptr
instead of std::unique_ptr
, it will do the same thing.