Is undefined behavior only an issue if you are deploying on several platforms?

前端 未结 12 951
谎友^
谎友^ 2020-12-24 10:47

Most of the conversations around undefined behavior (UB) talk about how there are some platforms that can do this, or some compilers do that.

What i

12条回答
  •  無奈伤痛
    2020-12-24 11:23

    There is a fundamental problem with undefined behavior of any kind: It is diagnosed by sanitizers and optimizers. A compiler can silently change behavior corresponding to those from one version to another (e.g. by expanding its repertoire), and suddenly you'll have some untraceable error in your program. This should be avoided.

    There is undefined behavior that is made "defined" by your particular implementation, though. A left shift by a negative amount of bits can be defined by your machine, and it would be safe to use it there, as breaking changes of documented features occur quite rarely. One more common example is strict aliasing: GCC can disable this restriction with -fno-strict-aliasing.

提交回复
热议问题