The codebase I work on has a bunch of code where an object might be deleted while one of its methods is running, with the method guaranteeing that it has stopped using the object's members by the time the delete happens. The most obvious example is a self-deleting object:
class SomeResource {
public:
SomeResource() = default;
void Close() {
// Read state before deleting.
const uint64_t id = id_;
delete this;
// Use what we read before.
std::cout << "Closed resource with ID " << id;
}
private:
// Delete via Close instead.
~SomeResource() = default;
const uint64_t id_ = MakeSomeID();
}
It seems intuitively fine to do this, since the delete is sequenced after the access to the member variable. But similar intuition might lead you to say it's okay to call a method via a null pointer as long as the method has null checks for this
, but that's not okay.
Less obvious situations include calling a function in another translation unit that causes the object to be deleted, or communicating with another thread, causing the object to be deleted.
Does the C++ standard say anything about whether it is or isn't allowed to delete an object while a member function is running? I'm looking for answers in standardese.