Question

I am trying to understand how destruction works in this simple case:

class A {
public:
    A(int i) { this->b = i; }
    void p() { std::cout << a << " " << b << std::endl;}
private:
    string a = "42";
    int b = 0;
};

int main() {
    A* ap = nullptr;
    while (true) {
         A k(24);
         ap = &k;
         k.p();
         break;
    } // A out of scope, I expect any pointer to A to be invalidated.
ap->p(); // still callable, b has been freed but not a!?
}

How come ap does point to a partially valid object? What I am doing wrong and not understanding? Please explain accurately because I am new to c++. Thanks!

EDIT: Assuming I call p() in ~A(); will that be a safe thing to do?

Was it helpful?

Solution

How come ap does point to a partially valid object?

ap doesn't point to a partially valid object. This is UB. The code works, because even though k goes out of scope, the memory is unchanged.

What happens here, is that when k goes out of scope, the memory offset for free stack memory (where the next stack object will be placed) is changed, so k (the memory where k "was") remains in free stack space. Placing another object on the stack (after the loop) will probably invalidate the memory at the address in ap.

UB means that anything could happen (in this case, "anything" means that the memory pointed to by ap, still points to the address of the A::p function.

OTHER TIPS

C++ is not an inherently reference-counted language, so pointers aren't directly invalidated in any way when an object is destroyed. You're inducing undefined behavior, and anything can happen. The compiler is not required to diagnose this problem.

You can always call ap->p(), but your program will have undefined behavior if you cannot guarantee that ap points to a valid memory location that belongs to an instance of class A.

Undefined behavior means that your program can do anything, including crash, doing nothing, or doing anything else.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top