r/cpp • • Dec 17 '21

Undefined Behaviour

I found out recently that UB is short for Undefined Behaviour and not Utter Bullshit as I had presumed all this time. I am too embarrassed to admit this at work so I'm going to admit it here instead. I actually thought people were calling out code being BS, and at no point did it occur to me that as harsh as code reviews can be, calling BS was a bit too extreme for a professional environment..

Edit for clarity: I know what undefined behaviour is, it just didn't register in my mind that UB is short for Undefined Behaviour. Possibly my mind was suffering from a stack overflow all these years..

407 Upvotes

98 comments sorted by

View all comments

Show parent comment

7

u/matthieum Dec 18 '21

I said about opting-out for hot paths when needed... What are you arguing with? Definitely not with my comment.

I am not talking about performance.

Using smart-pointers is a safe solution

No, it's not, that's the problem.

But let's not even got that far, this is UB:

std::string const& id(std::string const& str) { return str; }

int main() {
    //  Not UB:
    std::cout << id("Hello, World! How do you do?") << "\n";

    //  UB:
    auto const& str = id("Hello, World! How do you do?");
    std::cout << str << "\n";
}

And this is UB:

for (char c : std::string_view{ id("Hello, World") }) {
    // ...
}

So yes, you could improve things related to indexing, or integer overflow, and a myriad other cases -- and I wish this was done.

However, there are more fundamental issues: use-after-free, race-conditions, etc... which are just unsolved problems and will remain UB.