c++ vs intel/clang参数传递顺序

g++ vs intel/clang argument passing order?

本文关键字:参数传递 顺序 clang vs intel c++      更新时间:2023-10-16

考虑以下代码(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;
}

您必须多次运行它,因为有时没有明显的差异。但当firstsecond的评价时间有明显差异时,在g++下的结果如下:

1363376239363175
1363376239363174

和以下Intel和clang:

1363376267971435
1363376267971436

表示在g++下,先求second参数,在intel和clang下,先求first参数。

根据c++ 11标准哪个是正确的?

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

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

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

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

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