How can I determine if a C++ object has been deallocated?

前端 未结 6 1775
情话喂你
情话喂你 2020-11-29 13:38

I have a previous question that was answered in which I describe difficulties catching an exception when I try to access an object that has been deallocated by a third-party

相关标签:
6条回答
  • 2020-11-29 13:55

    If you control all the code that accesses your object, then the proper way is to use boost::shared_ptr to manage the lifetime of the object and then boost::weak_ptr for any references that you expect to remain after the object is deleted.

    Looking at your other question about a third party library though, you may be stuck. If the library is prone to deleting the object as a side effect of other options, then likely you're not intended to keep those pointers around. Is there a reason that you can't re-fetch the object any time you need it, or at least after doing anything that may have deleted it?

    0 讨论(0)
  • 2020-11-29 13:57

    I think you're asking the wrong question. The question really ought to be:

    Why do I feel like I need to look at some address in order to find out whether the pointer pointing there refers to an object or to the garbage left after an ex-object was deleted?

    Honestly, you shouldn't be in that situation. If an object is deleted, why are you left with a pointer to its ex-address? Ideally, the pointer should be out of scope. If that isn't possible in your code, it should have been set to NULL.

    0 讨论(0)
  • 2020-11-29 13:57

    You can't. If the function you're using doesn't give you ways of knowing whether or not it deallocated the object itself, there's no way you can find out.

    Edit: Well, unless the object in question is an instance of your own class and you can modify the destructor like Adrian suggested.

    0 讨论(0)
  • 2020-11-29 14:04

    I don't think you can, at least not in a standard way. There is, as far as I know, no requirement that the heap manager be able to detect if an address has been previously returned.

    If there was, there would be no need to make it undefined what delete is to do with invalid pointers.

    0 讨论(0)
  • 2020-11-29 14:07

    You can't easily tell just by looking at the memory location if the object is still allocated or not. There might be some black magic tricks to do that, but a much cleaner way would be to build a call-back mechanism into the object's destructor.

    0 讨论(0)
  • 2020-11-29 14:16

    create a destructor that notifies upon desrtruction. It could even toggle a bool, if you wanted to check it during runtime.

    class free
    {
    
    public:
    
        ~free() { cout << "Im being freed " << endl; } //destructor output
    };
    

    This will output in console that its being freed. After being freed, any reference to it will be undefined behaviour, even if it appears to exist.

    0 讨论(0)
提交回复
热议问题