Destructor being called twice when being explicitly invoked

后端 未结 10 462
孤街浪徒
孤街浪徒 2020-11-30 11:10

I was experimenting with destructors in C++ with this piece of code:

#include 

struct temp
{
    ~temp() { std::cout << \"Hello!\" <         


        
10条回答
  •  孤独总比滥情好
    2020-11-30 11:28

    Destructor is meant to be called when an object goes out of scope if the object is in the stack as in this case or called when it is explicitly destructed with delete when the object is created on the heap with new operator at the first place.

    There is no way for the compiler or the run time system to keep track whether the destructor is called by you manually or not. Also it is a very bad practice to make a call to the destructor.

    If you want to do some manual cleaning (other than the object being deleted from memory or getting removed from the stack) before the object getting deleted you may do something like this.

    Here you want to allow the client to manually clean things, even before the object gets deleted. But in addition to that, you clean things if client misses to clean it.

    class A
    {
    public:
        A() : _closed(false)
        {}
    
        ~A()
        {
            close();
        }
    
        void close()
        {
            if (! _closed()) {
                // close file handles etc.
            }
        }
    
    private:
        bool _closed
    }
    

提交回复
热议问题