是否使用无效指针未定义行为初始化指针声明符?

Is initializing a pointer declarator with an invalid pointer undefined behavior?

简而言之,是否认为以下代码具有未定义的行为?

int main()
{
    int *p = <some invalid pointer value>;
}

编译示例,取如下代码:

int main()
{
    int *p = new int;
    delete p; // Now p has an invalid pointer value.
    int *q = p; // UB?
}

我对这个话题做了一些研究,所以这些是我目前找到的相关信息:

指针值(根据cppreference)可以是以下之一:

另外,根据cppreference,

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.

This thread addresses some uses of invalid pointers. Specifically, this answer mentions the Rationale document (C99),其中有如下段落(第 6.3.2.3 节):

Regardless how an invalid pointer is created, any use of it yields undefined behavior. Even assignment, comparison with a null pointer constant, or comparison with itself, might on some systems result in an exception.

我不确定 C++ 的情况如何,但我认为,鉴于链接线程上的答案,使用 无效指针会导致未定义行为。但是请注意,assignmentinitialization 不同,因此我不确定初始化是否被视为一种用途。

您自己几乎已经回答了这个问题:在 C++ 中,它是 实现定义,而不是 未定义。标准说 just what you quoted (which I found by consulting the appropriate index). It doesn’t matter whether it’s initialization: the lvalue-to-rvalue conversion 在指针对象上 明确地 构成使用。