gpt4 book ai didi

c++ - C 中 'allocated object having no declared type' 的 C++ 等价物是什么?

转载 作者:IT老高 更新时间:2023-10-28 22:30:21 27 4
gpt4 key购买 nike

我正在用 C++ 为我的 VM 编写内存管理器。好吧,更准确地说,VM 指令将使用嵌入式内存管理器编译成 C++。我在处理 C 方面更加自如,但现在我确实需要对异常处理的原生支持,这几乎是我使用 C++ 的唯一原因。

C 和 C++ 都有严格的别名规则,即不兼容类型的两个对象不得重叠,C 中的 union 有一个小异常(exception)。但要定义malloccallocalloca等内存分配函数的行为,C标准有以下段落。

6.5-6 The effective type of an object for an access to its stored value is the declared type of the object, if any. Allocated objects have no declared type. If a value is stored into an object having no declared type through an lvalue having a type that is not a character type, then the type of the lvalue becomes the effective type of the object for that access and for subsequent accesses that do not modify the stored value. If a value is copied into an object having no declared type using memcpy or memmove, or is copied as an array of character type, then the effective type of the modified object for that access and for subsequent accesses that do not modify the value is the effective type of the object from which the value is copied, if it has one. For all other accesses to an object having no declared type, the effective type of the object is simply the type of the lvalue used for the access.

这有效地使为任何类型使用原始分配的内存成为 C 中明确定义的行为。我试图在 C++ 标准文档中找到类似的段落,但找不到。我认为 C++ 在这方面有不同的方法。什么是 C 中“没有声明类型的已分配对象”的 C++ 等价物,C++ 标准如何定义它?

最佳答案

对于 C++,这在对象生命周期 [object.life] 中有描述;特别是:

The lifetime of an object of type T begins when:

  • storage with the proper alignment and size for type T is obtained, and
  • if the object has non-trivial initialization, its initialization is complete.

生命周期一直持续到存储被重用或对象被破坏:

A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor.

这有一个相当奇怪的暗示,未使用的分配存储(从 operator new 返回)包含适合该存储 block 的每个普通类型的对象,至少在使用该存储 block 之前.但是,与这种小疣相比,该标准更关心的是如何正确处理非平凡的类型。

关于c++ - C 中 'allocated object having no declared type' 的 C++ 等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31483064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com