为什么删除定义为“未定义行为"的不完整类型? [英] Why is the deletion of an incomplete type defined as "undefined behaviour"?

查看:68
本文介绍了为什么删除定义为“未定义行为"的不完整类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么删除不完整的类型定义为未定义的行为" ?

Why is the deletion of an incomplete type defined as "undefined behaviour"?

根据C ++规范;§5.3.5/5;

From the C++ specification; §5.3.5/5;

如果要删除的对象在删除时具有不完整的类类型,并且完整的类具有非平凡的析构函数或释放函数,则行为是不确定的.

给出代码示例(我知道为什么会出错);

Given the code example (I understand why it is an error);

class ABC;

int main()
{
    ABC* p = nullptr;
    delete p;
}

当gcc,clang和msvc都警告它是不完整的类型时,为什么将它定义为是未定义的行为?为什么不只是在此时出现错误,即为什么它不是可诊断的错误?

Why is it defined as being undefined behaviour when gcc, clang and msvc all warn on it being an incomplete type? Why not just error at that point, i.e. why is it not a diagnosable error?

推荐答案

表达式 delete p; 有两件事:

  1. 销毁包含 * p 的完整对象.
  2. 释放用于存储所述对象的内存.

如果您只知道对象的地址,而没有任何其他信息,则

第2项 可能是可行的.内存分配器只关心地址.但是确定完整对象的地址可能很困难;您本质上需要保证您实际上是在提供完整对象的地址.

Item 2 may be possible when all you know is the address of the object, without any further information. The memory allocator only cares about addresses. But determining the complete object's address may be difficult; you essentially need to promise that you are actually providing the address of a complete object.

但是还有更多.在取消分配对象的存储空间之前,必须运行析构函数(第1项).如果析构函数无效,那么不运行析构函数也是可以接受的,因为它具有与您运行析构函数相同的行为.但是,如果运行析构函数确实起作用,则省略第1项导联会导致未定义的行为,并且您需要知道完整的类型才能知道如何运行析构函数.偶然地,您还需要知道完整的类型,才能确定项目2的最派生对象的地址.

But there's more. Before deallocating the object's storage, you must run destructors (Item 1). If the destructor has no effect, then it is acceptable to not run destructors, since that has the same behaviour as if you did run them. But if running destructors does have an effect, omitting Item 1 leads do undefined behaviour, and you need to know the complete type in order to know how to run destrutors. Incidentially, you also need to know the complete type in order to determine the address of the most-derived object for Item 2.

这篇关于为什么删除定义为“未定义行为"的不完整类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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