Legal legacy code using pointers suddenly becomes UB

落爺英雄遲暮 提交于 2020-01-02 08:39:06

问题


Let's say we have this legacy code from 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
}

So basically pointer here is used to keep dynamically allocated data and use it as a flag at the same time. For me it is readable code and I believe it is legal C++98 code. Now according to this questions:

Pointers in c++ after delete

What happens to the pointer itself after delete?

this code has UB in C++11. Is it true?

If yes another question comes in mind, I heard that committee puts significant effort not to break existing code in new standard. If I am not mistaken in this case this not true. What is the reason? Is such code considered harmfull already so nobody cares it would be broken? They did not think about consequences? This optimization is so important? Something else?


回答1:


Your example exhibits undefined behavior under C++98, too. From the C++98 standard:

[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.



来源:https://stackoverflow.com/questions/44191920/legal-legacy-code-using-pointers-suddenly-becomes-ub

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!