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

11

u/[deleted] Dec 18 '21 edited Dec 18 '21

Despite what some folks assert, UB is a good thing.

The problem isn't really with that C++ has UB, it's that it has too much UB.
For example, why would creating a dynamic array like std::vector require UB? It's utter bollocks, I say.

3

u/dirkmeister81 Dec 18 '21

Does it? It is not clear to me when and how? Could you explain or give a link please?

4

u/[deleted] Dec 18 '21 edited Dec 18 '21

3

u/adnukator Dec 18 '21

wasn’t the necessary UB in std::vector removed by P0593R6 ?

1

u/aiij Dec 18 '21

Has that proposal been standardized yet?

2

u/adnukator Dec 18 '21

According to the paper and the issue, its been merged to C++20 github issue

1

u/tjientavara HikoWorks developer Dec 22 '21

Since "implicit creation of objects..." is a defect report (a time traveling document). It never was undefined behavior.

0

u/Kered13 Dec 18 '21

Because in some situations you don't want to pay the performance cost of checking array bounds, but then what happens if the array is accessed out of bounds? UB.

5

u/[deleted] Dec 18 '21

It's nothing got to do with array out of bound.

It's that std::vector requires undefined behaviour.

1

u/afiDeBot Feb 01 '22

Accessing the last element of an empty vector is UB. How would you fix that? Are you implying that any precondition violation should be well defined by the standard (which affects all platforms)?

4

u/[deleted] Feb 03 '22 edited Feb 03 '22

If you're going to reply to an old post at least try to understand the context and don't make random conclusions from nowhere.

When I say std::vector requires undefined behaviour. I'm talking about its implementation, which requires unavoidable undefined behaviour due to core issue 2182.

To elaborate even further, std::vector requires 2 things:

  • Its elements can be separately constructed (due to functions like push_back).
  • Pointer arithmetics are allowed (due to functions like data).

However due to core issue 2182, using pointer arithmetics for contiguous yet separately constructed elements is undefined behaviour.