Does calling a destructor explicitly destroy an object completely?

前端 未结 11 1432
日久生厌
日久生厌 2020-12-03 14:43

If I call a destructor explicitly ( myObject.~Object() ) does this assure me that the object will be appropriately destroyed (calling all child destructors) ?

Ok so

11条回答
  •  既然无缘
    2020-12-03 15:24

    Yes it will call all the child destructors so it will work as you are expecting.

    The destructor is just a function after all, it just so happens that it gets called when objects are deleted.

    Therefore if you use this approach be careful of this:

    #include 
    
    class A
    {
    public: 
        A(){};
        ~A()
        {
            std::cout << "OMG" << std::endl;
        }
    };
    
    int main()
    {
        A* a = new A;
        a->~A();
        delete a;
        return 0;
    }
    
    output:
    OMG
    OMG 
    

    The destructor is called a second time when delete is actually called on the object, so if you delete pointers in your destructor, make sure that you set them to 0, so that the second the destructor is called nothing will happen (as deleting a null pointer does nothing).

提交回复
热议问题