使用指针的合法遗留代码突然变成了 UB

Legal legacy code using pointers suddenly becomes UB

假设我们有来自 C++98 的遗留代码:

bool expensiveCheck();

struct Foo;

bool someFunc()
{
    Foo *ptr = 0;
    if( expensiveCheck() )
        ptr = new Foo;

    // doing something irrelevant here
    ...
    if( ptr ) {
        // using foo
    }
    delete ptr;
    return ptr; // here we have UB(Undefined Behavior) in C++11
}

所以基本上这里的指针是用来保存动态分配的数据,同时作为标志使用的。对我来说,它是可读的代码,我相信它是合法的 C++98 代码。现在根据这个问题:

Pointers in c++ after delete

What happens to the pointer itself after delete?

此代码在 C++11 中有 UB。是真的吗?

如果是,我想到另一个问题,我听说委员会付出了巨大的努力,不破坏新标准中的现有代码。如果我没记错的话,这不是真的。是什么原因?这样的代码是否已经被认为是有害的,所以没有人关心它会被破坏?他们没有想过后果吗?这个优化这么重要?还有别的吗?

您的示例在 C++98 下也表现出未定义的行为。来自 C++98 标准:

[basic.stc.dynamic.deallocation]/4 If the argument given to a deallocation function in the standard library is a pointer that is not the null pointer value (4.10), the deallocation function shall deallocate the storage referenced by the pointer, rendering invalid all pointers referring to any part of the deallocated storage. The effect of using an invalid pointer value (including passing it to a deallocation function) is undefined.33)

Footnote 33) On some implementations, it causes a system-generated runtime fault.