C++ assertion error while deleting object

前端 未结 3 480
伪装坚强ぢ
伪装坚强ぢ 2020-12-22 06:28

I have strange assertion error and I can not find what is wrong with this code.

Assertion expression is _BLOCK_TYPE_IS_VALID(pHead->nBlockUse).

I simplified

3条回答
  •  青春惊慌失措
    2020-12-22 06:53

    The issue is that your MyObject class lacks a virtual destructor, and you're attempting to call delete on a pointer to the derived class using a pointer to the base class MyObject. Issuing a delete on a derived object through a base class pointer is undefined behavior if the base class destructor is not virtual.

    5.3.5 Delete (Paragraph 3)

    In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.

    Once the destructor is made virtual in the base class MyClass, the following works correctly in Visual Studio 2013:

    #include 
    struct MyObject 
    {
        virtual ~MyObject() {}
    };
    
    class Creator
    {
    public:
        virtual ~Creator()
        {
            for (MyObject* item : _list)
            {
                delete item; 
                item = 0;
            }
            _list.clear();
        }
    
        template 
        T& create()
        {
            T * item = new T();
            _list.push_back(item);
            return *item;
        }
    
    private:
        std::list _list;
    };
    
    class A : public MyObject, public Creator
    {
    };
    
    class B : public MyObject, public Creator
    {
    };
    
    int main()
    {
        A a;
        a.create();
    } 
    

提交回复
热议问题