-1

I've been playing with some code recently and I've been curious about one thing that I'm not sure I've figured out a correct answer to. So, let's assume that I've defined the following class.

class Thing {
public:
    int m_Integer = 0;

    Thing() {
        std::cout << "Thing constructor has been called! Address: " << this << ".\n ";
    }

    ~Thing() noexcept {
        std::cout << "Thing destructor has been called! Address: " << this << ".\n";
    }

    static Thing CreateInstance() {
        return Thing();
    }

    void* GetThis() {
        return this;
    }
};

I've explicitly defined default ctor and dtor to see whether these were called. OK, then, I've created a handle.

void* hThing = Thing::CreateInstance().GetThis();

Logs tell me that both constructor and destructor have been called. Does this mean that I've allocated some memory on stack, which has a layout like Thing type object but the object itself is no more?

J. White
  • 61
  • 6
  • You've created a temporary object and obtained a pointer to this object which immediately becomes invalid as object goes out of scope. There are no handles of any kind involved here. – user7860670 Apr 19 '19 at 09:11
  • The thing is that me having a pointer to this object allows me to cast it to Thing type and see what's behind it. To my suprise, this there's no garbate there and everything looks find as if the destructor weren't called. That's what bothers me. – J. White Apr 19 '19 at 09:18
  • Accessing value pointed to by this pointer is Undefined Behavior. It is wrong to have any expectations for results of such an action. – user7860670 Apr 19 '19 at 09:20
  • Ok, thank you for your answers. – J. White Apr 19 '19 at 09:30

1 Answers1

3

Thing::CreateInstance() returns a local object inside it, and after GetThis(), the object will be destroyed by system automatically(call destructor). The hThing you have got is an unexpected address value. The pointing space has been freed from the stack by the system, and the value can be modified at any time.

Drake Wu
  • 6,927
  • 1
  • 7
  • 30
  • Fine, that's what I've thought at the very beginning, but as I've done this... Thing* pThing = static_cast( hThing) ; ...and checked value of Thing type member, it seemed just fine. That's led me to a conclusion that I must be missing something important here. – J. White Apr 19 '19 at 09:29
  • @J.White Yes, If there is no allocation of stack space by system in following, the member value will not change, but the system may allocate this **free** memory to others at any time with any value. – Drake Wu Apr 19 '19 at 09:40