gpt4 book ai didi

c++ - 是否使用定义的任意、文字、非零值初始化指针?

转载 作者:搜寻专家 更新时间:2023-10-31 00:27:02 27 4
gpt4 key购买 nike

考虑:

struct T{};

int main() {
T* p = (T*)0xDEADBEEF;
}

使用无效指针是实现定义的。取消引用它是未定义的行为。我的问题与这些无关。

我的问题是 p 的初始化是否按原样定义。

如果您认为您已经拥有回答此问题所需的所有信息(或者如果您发现这是重复的),则无需进一步阅读。以下是基于我的发现的一些嘀咕:

C 标准(C++ 标准基于此)说:

6.3.2.3 Pointers

5   An integer may be converted to any pointer type. Except as previously specified, theresult is implementation-defined, might not be correctly aligned, might not point to anentity of the referenced type, and might be a trap representation.

这暗示它可能是实现定义的。

C++ 标准仅定义(据我所知)任何对无效指针值 的使用都是实现定义的。脚注特别重要,因为它似乎暗示这种值的单纯复制 已经是对指针的使用。 (还是指指向值?我很困惑)

6.7 Storage duration

4   When the end of the duration of a region of storage is reached, the values of all pointers representing the address of any part of that region of storage become invalid pointer values (6.9.2). Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior.37

37 Some implementations might define that copying an invalid pointer value causes a system-generated runtime fault

这种符合C标准。问题是我不相信这是一个无效指针值的例子,因为标准明确指出这种类型的值是由到达该地址的存储持续时间结束引起的(这显然从未发生过)。

还有许多指针算术实例是未定义行为TM,但显然没有算术或在这里对指针的值进行操作。这只是一个初始化。

最佳答案

您的 C 风格转换正在执行 reinterpret_cast;像这样类型转换一个任意整数值是 implementation-defined :

8.5.1.10 Reinterpret cast

5   A value of integral type or enumeration type can be explicitly converted to a pointer. A pointer converted to an integer of sufficient size (if any such exists on the implementation) and back to the same pointer type will have its original value; mappings between pointers and integers are otherwise implementation-defined. [ Note: Except as described in [basic.stc.dynamic.safety], the result of such a conversion will not be a safely-derived pointer value. — end note ]

如果结果是(被实现认为是)一个无效的指针值,那么它可能又是implementation-defined当它存储在变量中时会发生什么,但不太清楚:

6.6.4 Storage duration

4   When the end of the duration of a region of storage is reached, the values of all pointers representing the address of any part of that region of storage become invalid pointer values.Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior.Any other use of an invalid pointer value has implementation-defined behavior.

关于c++ - 是否使用定义的任意、文字、非零值初始化指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50548352/

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