When is it okay to do/use something that has unspe

2019-09-21 06:59发布

问题:

This question already has an answer here:

  • Undefined, unspecified and implementation-defined behavior 9 answers

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.