c++ - 这里有更多 C++ 中未定义的行为,很抱歉这个问题,但又是 UB

标签 c++ c++11 language-lawyer undefined-behavior

有一个非常简单的 UB 例子:

int i = 1;
i = i++; // classic example of UB.

我最近看到,如何使用 Pascal 风格的 inc 操作。 Eric Niebler github

// this structure little difference than original.
struct inc_t 
{   
  template< typename T> 
  T operator()(T& t ) const { return t++; } 
};

constexpr inc_t inc{};

//usage
int i = 1;
inc(i);
//or
int j = inc(i);

所以,合并:

int i = 1;
i = inc(i); // Is there still UB ?

谢谢。

最佳答案

i = i++ 是 UB 因为 i 递增时没有指定;它可以在 i++值计算之后的任何时候(i 的左值到右值的转换>) 和完整表达式结束之前。因此,相对于赋值语句,此写入是无序的。对同一 int 的两次无序写入是未定义的行为。

但在 i = inc(i) 中,i 的递增发生在函数返回之前,因为 t++ 中的完整表达式发生在函数内部。反过来,函数必须在右侧的值计算之前返回,并且赋值在两侧的值计算之后排序。因此i的递增顺序在赋值之前,没有UB。

C++11标准的相关引述:

§1.9/14

Every value computation and side effect associated with a full-expression is sequenced before every value computation and side effect associated with the next full-expression to be evaluated.

§5.17/1

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

关于c++ - 这里有更多 C++ 中未定义的行为,很抱歉这个问题,但又是 UB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22076038/

相关文章:

c++11 decltype 返回引用类型

c++ - 可以推断左值引用非类型模板参数吗?

c++ - 字节真的是最小可寻址单位吗?

c++ - 是什么导致 poll() 函数出现错误,C++?

C++ "No matching function for call"错误

c++ - 是否有原因 declval 返回 add_rvalue_reference 而不是 add_lvalue_reference

c++ - 概念是由看似会产生无效表达式的类型满足的

c++ - CUDA 在使用函数指针时将主机函数作为内核启动

c++ - 在 C/C++ 中增量动态分配内存

c++ - 当类被销毁时,在类中声明的 map 容器是否被销毁?