什么时候可以做/使用有未指定行为的东西? [英] When is it okay to do/use something that has unspecified behaviour?

查看:223
本文介绍了什么时候可以做/使用有未指定行为的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,有些东西出现在明确定义和未定义之间。具体来说,这些被称为实现定义未指定。现在,我对未指定的内容感兴趣。



什么时候可以使用这些功能,什么时候应该避免?有没有良好的未指定行为的例子是正确的代码的一部分?



由Matt McNabb提供的定义:




  • 未定义 - 可以发生任何事情



  • 未指定 - 有限数量的结果是可能的 - 通常标准描述了可能的结果集


  • 明确定义 - 以上都不是


  • 组织良好的计划 - 无错编译的程序(可能会显示未定义的行为)







$ b strong> 标记为从不同角度讨论同一个想法的问题的重复。
> >

解决方案

要回答新的问题,什么时候可以使用未指定的行为?



这可能听起来微不足道,



例如,

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

如果你不在乎你看到foobar3还是barfoo3码。如果它不重要,那么你必须改变它,例如

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

顺序是未指定的,因为它是好的让编译器自由选择无论哪个顺序是最佳的,更一般的情况。


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.

解决方案

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.

这篇关于什么时候可以做/使用有未指定行为的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆