在 C++ 中使用逗号运算符时的未定义行为

Undefined Behavior when using Comma Operator in C++

我正在尝试了解如何在 C++ 中计算表达式。所以尝试和阅读不同的例子。下面是我无法理解它是否会产生未定义行为的代码。代码来自here。所以我想既然他们用过它,这一定不是 UB。但是我有疑问。

#include <iostream>
int main()
{
    int n = 1;
    //std::cout << n << " " << ++n << std::endl;//this is undefined behavior i am sure
    int m = (++n, std::cout << "n = " << n << '\n', ++n, 2*n);//will this also produce UB because here also we have cout in the same manner as above?
    std::cout << "m = " << (++m, m) << '\n';
}

正如您在上面的代码中看到的,我确信语句:

cout << n << " " << ++n << endl;

产生未定义的行为。 我的问题是:

  1. 但是逗号运算符内部使用的相同语句会产生UB吗(如上面的代码所示)?也就是说,下面给出的语句是否会产生 UB.
int m = (++n, std::cout << "n = " << n << '\n', ++n, 2*n);
  1. 我们如何解释上面提到的语句的行为在前序、未排序等方面的情况。

PS:我知道自从 C++11 以来,我们使用 sequence-before 等而不是序列点,所以我问为什么要根据当前标准进行解释。

来自 cppreference 的同一页面:

In a comma expression E1, E2, the expression E1 is evaluated, its result is discarded (although if it has class type, it won't be destroyed until the end of the containing full expression), and its side effects are completed before evaluation of the expression E2 begins (note that a user-defined operator, cannot guarantee sequencing) (until C++17).

由于代码中的逗号运算符是内置的,因此 ++nstd::cout << "n = " << n << '\n' 和其他表达式之间的顺序定义明确。没有未定义的行为。

因为您可能已经阅读了上面的内容,这里是 wording from the standard:

A pair of expressions separated by a comma is evaluated left-to-right; the left expression is a discarded-value expression. The left expression is sequenced before the right expression ([intro.execution]).