Delete objects of incomplete type

前端 未结 3 2010
孤街浪徒
孤街浪徒 2020-12-06 16:02

This one made me think:

class X;

void foo(X* p)
{
    delete p;
}

How can we possibly delete p if we do not even know whether

3条回答
  •  暖寄归人
    2020-12-06 16:42

    It is undefined behavior.

    However, you can make the compiler check for incomplete types, like boost:

    // verify that types are complete for increased safety
    
    template inline void checked_delete(T * x)
    {
        // intentionally complex - simplification causes regressions
        typedef char type_must_be_complete[ sizeof(T)? 1: -1 ];
        (void) sizeof(type_must_be_complete);
        delete x;
    }
    

    Applying sizeof to an incomplete type should trigger an error, and I suppose if that passes with some compiler, then an array of negative size would trigger an error.

提交回复
热议问题