jeudi 25 mai 2017

Legal legacy code using pointers suddenly becomes UB

Let's say we have this legacy code from C++98:

bool expensiveCheck();

struct Foo;

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

    // doing something irrelevant here
    ...
    if( ptr ) {
        // using foo
    }
    delete ptr;
    return ptr; // here we have UB 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?

Aucun commentaire:

Enregistrer un commentaire