c++ - 这段代码定义明确吗?

标签 c++ c++11 sequence-points operator-precedence

我怀疑根据 C++ 标准(假设 C++0x),以下函数链接会导致未指定的序列。只是想要确认,如果有人可以提供解释,我将不胜感激。

#include <iostream>

struct TFoo 
{
    TFoo(int) 
    {
        std::cout<<"TFoo"<<std::endl;
    };
    TFoo foobar1(int) 
    {
        std::cout<<"foobar1"<<std::endl;
        return *this;
    };
    TFoo foobar2(int) 
    {
        std::cout<<"foobar2"<<std::endl;
        return *this;
    };
    static int bar1() 
    {
        std::cout<<"bar1"<<std::endl;
        return 0;
    };
    static int bar2() 
    {
        std::cout<<"bar2"<<std::endl;
        return 0;
    };
    static int bar3()
    {
        std::cout<<"bar3"<<std::endl;
        return 0;
    }
};

int main(int argc, char *argv[])
{
    // is the sequence well defined for bar1, bar2 and bar3?
    TFoo(TFoo::bar1()).foobar1(TFoo::bar2()).foobar2(TFoo::bar3());
}

* 编辑:删除了函数的 __fastcall 说明符(不需要/与问题无关)。

最佳答案

未指定评估顺序。草案相关部分C++0x spec是 1.9,第 14 和 15 段:

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.

15 Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced.

这里相关的完整表达式是:

TFoo(TFoo::bar1()).foobar1(TFoo::bar2()).foobar2(TFoo::bar3());

因此对其子表达式的求值是无序的(除非在某处指出了我遗漏的异常)。

我很确定早期的标准包括具有相同效果但在“序列点”方面的语言。

[编辑]

第 15 段还说:

When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function. [Note: Value computations and side effects associated with different argument expressions are unsequenced.— end note]

“指定被调用函数的后缀表达式”类似于 foo().bar() 中的 foo().bar

此处的“注释”只是阐明参数评估顺序不是“未指定顺序”默认值的异常(exception)。据推论,与“指定被调用函数的后缀表达式”相关联的求值顺序也不存在;或者,如果您愿意,this 参数的表达式的求值顺序。 (如果有异常,这将是指定它的自然位置。或者可能是讨论函数调用的第 5.2.2 节。这两个部分都没有说明此示例的评估顺序,因此未指定。)

关于c++ - 这段代码定义明确吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6687390/

相关文章:

c++ - 使用 Makefile.am/Makefile.in 在 Ubuntu Linux 中构建 C++ 项目

c++ - 具有可以抛出的 move 操作的仅 move 类的示例是什么?

c++ - 如何在最后一个窗口关闭时保持应用程序运行?

表示库中项目的类的 c++ 派生类

c++ - 错误 : MFC projects cannot define _ATL_NO_EXCEPTIONS

c++ - 为什么 clang 4.0 不捕获标准异常?

c++ - 是否允许在 constexpr 函数中进行函数指针比较?

c++ - 在 C++17 中排序的移位操作数

c++ - 在 C++17 中,这段代码应该产生警告吗?

c - 为什么这些构造使用增量前和增量后未定义的行为?