简体   繁体   English

这是未定义的行为吗?

[英]Is this undefined behavior or not?

class A
{
public:
    int i;
    ~A()
    {   
        std::cout << "~A" << std::endl;
    }   
};

class B: public A
{
public:
    int k;
    ~B()
    {   
        std::cout << "~B" << std::endl;
    }   
};

int main(int argc, char* argv[])
{
    A* p = new B();
    delete p;
    return 0;
}

The above doesn't cause memory leak though base destructor is not virtual and I know the reason. 尽管基本析构函数不是虚拟的,但以上所述不会导致内存泄漏,我知道原因。

But is this undefined behavior or not? 但这是未定义的行为吗?

Say there won't be memory leak if derived class doesn't point to other dynamic data even though base destructor is non-virtual? 假设即使基本析构函数不是虚拟的,如果派生类没有指向其他动态数据,也不会发生内存泄漏?

Yes it is . 是的,是的 Deleting an object of a derived class through a pointer to a base class with no virtual destructor is textbook UB. 通过没有virtual析构函数的基类的指针删除派生class的对象是教科书UB。

5.3.5/3: 5.3.5 / 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. 在第一个替代方案(删除对象)中,如果操作数的静态类型不同于其动态类型,则静态类型应为操作数动态类型的基类,并且静态类型应具有虚拟析构函数或行为未定义。 In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.73) 在第二种选择(删除数组)中,如果要删除的对象的动态类型不同于其静态类型,则行为是不确定的(73)。

Because it's undefined behavior, it doesn't really make sense to guess whether the code will leak or not. 因为它是未定义的行为,所以猜测代码是否会泄漏实际上没有任何意义。 Just attempt to fix the code instead of predicting results. 只是尝试修复代码而不是预测结果。

Yes, since the static type (here it's A ) differs from the dynamic type ( B in your example) and there's no virtual destructor, it's an UB. 是的,因为静态类型(此处为A )与动态类型(本例中为B )不同,并且没有virtual析构函数,所以它是UB。

5.3.5/2 (5.3.5/3 in C++11): 5.3.5 / 2(在C ++ 11中为5.3.5 / 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. 在第一个替代方案(删除对象)中,如果操作数的静态类型不同于其动态类型,则静态类型应为操作数动态类型的基类,并且静态类型应具有虚拟析构函数或行为未定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM