为什么 C++20 中的 [[likely]] 属性会在此处引发警告?
Why [[likely]] attribute in C++20 raises a warning here?
#include <iostream>
int foo(int a, int b)
{
if(a < b) [[likely]] {
return a;
}
return b;
}
int main()
{
std::cout << foo(3,1) << std::endl;
}
根据参考资料,这似乎是我们应该如何用 [[likely]]
或 [[unlikely]]
属性装饰 if
子句。 C++20 也支持它(参见 here)。
但是,我 运行 收到警告:
main.cpp: In function 'int foo(int, int)':
main.cpp:5:15: warning: attributes at the beginning of statement are ignored [-Wattributes]
5 | if(a < b) [[likely]] {
| ^~~~~~~~~~
代码库对警告很严格,这会导致构建失败。那么,我做错了什么,还是这是一个错误?
我的 macbook 上的 g++ 版本:
g++-9 (Homebrew GCC 9.3.0_1) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
您的代码没有任何问题。这是由于 GCC 的实现者 overlooking the fact that attributes on compound-statements are a thing.
[[likely]] if (whatever) {}
完全是另外一种意思 - 它意味着 if
语句本身是 "likely",而不是它的一个分支。
#include <iostream>
int foo(int a, int b)
{
if(a < b) [[likely]] {
return a;
}
return b;
}
int main()
{
std::cout << foo(3,1) << std::endl;
}
根据参考资料,这似乎是我们应该如何用 [[likely]]
或 [[unlikely]]
属性装饰 if
子句。 C++20 也支持它(参见 here)。
但是,我 运行 收到警告:
main.cpp: In function 'int foo(int, int)': main.cpp:5:15: warning: attributes at the beginning of statement are ignored [-Wattributes] 5 | if(a < b) [[likely]] { | ^~~~~~~~~~
代码库对警告很严格,这会导致构建失败。那么,我做错了什么,还是这是一个错误?
我的 macbook 上的 g++ 版本:
g++-9 (Homebrew GCC 9.3.0_1) 9.3.0 Copyright (C) 2019 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
您的代码没有任何问题。这是由于 GCC 的实现者 overlooking the fact that attributes on compound-statements are a thing.
[[likely]] if (whatever) {}
完全是另外一种意思 - 它意味着 if
语句本身是 "likely",而不是它的一个分支。