delete a NULL pointer does not call overloaded delete when destructor is written

前端 未结 7 2042
慢半拍i
慢半拍i 2021-02-02 15:05
class Widget
{
    public:
        Widget() {
            cout<<\"~Widget()\"<

        
相关标签:
7条回答
  • 2021-02-02 15:33

    The reason is that if you have a destructor, the call to the delete operator is done from within the scalar deleting destructor, which in VC contains the call to both your destructor and the delete operator. The compiler provides code that checks whether you're trying to delete a NULL pointer. Deleting such pointer is legal, of course, but the destructor of such object must not be invoked, as it might contain usage of member variables. For that the call to the scalar deleting destructor is avoided, and as a result the call to the delete operator is avoided as well.

    When there is no destructor, the compiler just calls the delete operator directly, without generating the scalar deleting destructor. Therefore, in such cases the delete operator is invoked after all.

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