非虚拟析构函数的不确定行为-这是现实问题吗? [英] Undefined behaviour with non-virtual destructors - is it a real-world issue?

查看:264
本文介绍了非虚拟析构函数的不确定行为-这是现实问题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下代码:

class A 
{
public:
  A() {}
  ~A() {}
};

class B: public A
{
  B() {}
  ~B() {}
};

A* b = new B;
delete b; // undefined behaviour

我的理解是C ++标准说删除b是未定义的行为-即, 任何事情都可能发生。但是,在现实世界中,我的经验是〜A()总是被 调用,并且内存已正确释放。

My understanding is that the C++ standard says that deleting b is undefined behaviour - ie, anything could happen. But, in the real world, my experience is that ~A() is always invoked, and the memory is correctly freed.

如果B引入任何带有自己的析构函数的类成员,它们不会被调用,但是我只对上面的简单情况感兴趣,在这种情况下,可以使用继承来修复一个源代码不可用的类方法中的错误。

if B introduces any class members with their own destructors, they won't get invoked, but I'm only interested in the simple kind of case above, where inheritance is used maybe to fix a bug in one class method for which source code is unavailable.

显然,在非平凡的情况下,这不是您想要的,但这至少是一致的。对于显示的代码,您是否知道不会发生上述任何事情的任何 C ++实现?

Obviously this isn't going to be what you want in non-trivial cases, but it is at least consistent. Are you aware of any C++ implementation where the above does NOT happen, for the code shown?

推荐答案

这在C ++标记中是一个永无止境的问题:什么是可预测的未定义行为。轻松自己解决所有问题:获取每个 C ++编译器实现,并检查可预测的不可预测是否仍然有效。但是,这是您必须自己完成的事情。

This is a never-ending question in the C++ tag: "What is the predictable undefined behavior". Easy to resolve all by yourself: get every C++ compiler implementation and check if the predictable unpredictable still works. This is however something you have to do by yourself.

一定要发回发现的内容,这对您很有用。只要不可预测的行为在整体上具有一致且带注释的行为。这对于编写C ++编译器的人来说真的很难使任何人都关注他的产品。按照约定进行标准化,发生 lot 且其语言具有未定义行为的 lot

Do post back what you found out, that would be quite useful to know. As long as the unpredictable has consistent and annotated behavior across the board. It makes it really hard for somebody that writes a C++ compiler to get anybody to pay attention to his product. Standardization by convention, happens a lot with a language that has a lot of undefined behavior.

这篇关于非虚拟析构函数的不确定行为-这是现实问题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆