Explicitly Invoking the Destructor

closed account (zb0S216C)
After invoking a destructor, what would happen if we referenced the destroyed variable in this manner:

1
2
3
4
5
6
7
8
9
10
11
12
13
struct Basic
{
    int Member;
};

int main()
{
    Basic A, *P(&A);

    P->~Basic();

    A.Member = 10; // Ah, awkward.
}

Does this code force the stack to pop A from the current stack frame? Or something else?

Please, no lectures on "You shouldn't inkove destructors!" I do know that you should invoke destructors when using placement new, however.

Wazzak
> After invoking a destructor, what would happen if we referenced the destroyed variable

It would lead to 'undefined behaviour'. In layman's terms, anything may happen.


closed account (zb0S216C)
Thanks for the reply, JLBorges. But what about the stack? How does it affect it?

Wazzak
> But what about the stack? How does it affect it?

In practice, the memory occupied by the object object would remain as raw uninitialized memory till the local scope of the object is exited. At that point, the destructor would be called once again, on an object that does not exist. If the object has a trivial destructor nothing perceptibly untoward would happen - and the memory would then be reclaimed. If not, it just depends on what the particular destructor tries to do.


Note: The C++ standard makes no mention of a 'stack'. Instead, it uses the abstract concept of 'storage durations' to define the minimum potential lifetime of the storage containing the object. An implementation can store all the objects in a program on a stack, or on a heap, or anywhere else it pleases for that matter - as long as it can ensure that the lifetime of objects conform to the storage durations (automatic, static, dynamic or thread) as specified by the IS.
closed account (zb0S216C)
Thanks, JLBorges.

Wazzak
After invoking a destructor, what would happen if we referenced the destroyed variable
Nothing particular happens. A desturctor invoked this way is just another function call. It does whatever the destructor does.

The object itself doesn't become invalid because the underlying memory is not free'd. So this A.Member = 10; can be done without problem. The destructor is called again when the object goes out of scope (and this time the object really gets invalid)
Topic archived. No new replies allowed.