When is it okay to do/use something that has unspecified behaviour? [duplicate]

丶灬走出姿态 提交于 2019-12-13 09:20:45

问题


In C++, there are things that come up that are somewhere between well-defined and undefined. Specifically, those are called implementation defined and unspecified. Right now, I'm interested in the unspecified stuff.

When is it okay to use such features, and when should they be avoided? Are there good examples of unspecified behaviour being a part of correct code? When, if ever, is it the best choice to make when writing software?

Definitions provided by Matt McNabb:

  • Undefined - anything at all can happen

  • Implementation-defined - a finite number of results are possible, and the compiler's documentation must say what happens

  • Unspecified - a finite number of results are possible -- usually the Standard describes the set of possible results

  • Well-defined - none of the above

  • Well-formed program - program that compiles without error (may exhibit undefined behaviour)

Follow-up question:

Do relaxed atomics count as unspecified or well-defined?

Marked as a duplicate of a question that talks about the same idea from a different perspective. The question marked as the same talks about the definition of unspecified behaviour, whereas here the question is about how and when to use it.


回答1:


To answer the new question, "When is it OK to use unspecified behaviour?"

It may sound slightly facetious, but "any time it doesn't matter to you which option happens".

For example,

int foo() { cout << "foo"; return 1; }
int bar() { cout << "bar"; return 2; }
// ...
cout << (foo() + bar()) << "\n";

If you don't care whether you see "foobar3" or "barfoo3" then you could write this code. If it does matter then you would have to change it, e.g.

int i = foo(); i += bar(); cout << i << "\n";

The order is unspecified because it's good to leave freedom for the compiler to choose whichever order is optimal, in a more general case.



来源:https://stackoverflow.com/questions/24813218/when-is-it-okay-to-do-use-something-that-has-unspecified-behaviour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!