7

考虑以下代码(LWS):

#include <iostream>
#include <chrono>

inline void test(
   const std::chrono::high_resolution_clock::time_point& first, 
   const std::chrono::high_resolution_clock::time_point& second)
{
   std::cout << first.time_since_epoch().count() << std::endl;
   std::cout << second.time_since_epoch().count() << std::endl;
}

int main(int argc, char* argv[])
{
   test(std::chrono::high_resolution_clock::now(), 
        std::chrono::high_resolution_clock::now());
   return 0;
}

您必须多次运行它,因为有时没有明显的区别。first但是当和的求值时间有明显差异时,second在 g++ 下的结果如下:

1363376239363175
1363376239363174

以及 intel 和 clang 下的以下内容:

1363376267971435
1363376267971436

这意味着在 g++ 下,second首先评估参数,而在 intel 和 clang 下,first首先评估参数。

根据 C++11 标准,哪一个是正确的?

4

2 回答 2

14

根据 C++11 标准,哪一个是正确的?

两者都是允许的。引用标准(§8.3.6):

函数参数的求值顺序未指定。

于 2013-03-15T19:41:49.840 回答
0

我有一个稍微简单的例子来说明同样的问题。

bash$ cat test.cpp
#include <iostream>
using namespace std;
int x = 0;
int foo() 
{
    cout << "foo" << endl;
    return x++;
}
int bar()
{
    cout << "bar" << endl;
    return x++;
}
void test_it(int a, int b)
{
    cout << "a = " << a << endl
        << "b = " << b << endl;

}
int main(int argc, const char *argv[])
{
    test_it(foo(),bar()); 
    return 0;
}

bash$ clang++ test.cpp && ./a.out
foo
bar
a = 0
b = 1
bash$ g++ test.cpp && ./a.out
bar
foo
a = 1
b = 0
于 2013-11-16T16:15:11.563 回答