Do we sometimes have to write code that has undefined behavior according to the C++ Standard?

c++, c++11, function-pointers, undefined-behavior

Solution

Nobody forces you to write anything, so nobody forces you to write code that invokes UB.

As for the standard library, its code is free to contain any nonportable behavior it wants - heck, it may even be written in another language with the compiler creating the bindings via magical unicorns; all that matters is that it behaves according to specification.

Come to think of it, it's obvious that at some level the standard library will have to go outside the standard - making syscalls, talking with hardware, ... is not even contemplated by the standard, and is often deeply platform-specific. For example, on 64 bit Linux you can perform syscalls with inline assembly (via the `sysenter` instruction) - the standard does not forbid this, it just doesn't mandate that every platform must behave like this.

As for the specific example, I don't see any UB - the `union`s there are used as specified by the standard - i.e. reading only from the last member you wrote into (hence the field `m_flag`).

Problem

In regard to C++ Standard: - Does `std::function` of GNU Compiler Collection use `union` data type to cast between different function pointer types (e.g. to convert non-static member function pointer to non-member function pointer)? I think so. EDIT: It uses `union` data type but no cast is made (type-erasure). - Is it an `undefined behavior` to cast between different function pointer types (in C++ or C++11 Standard)? I think so. - Is it possible to implement a `std::function` without using any code which has an `undefined behavior`? I don't think so. I'm talking about this. The following is my question: Do we sometimes have to write code that has `undefined behavior` according to the C++ Standard (but they have `defined behavior` for particular C++ compilers such as GCC or MSVC)? Does it mean that we can't/shouldn't prevent `undefined behavior` of our C++ codes?

Original source

Related problems