[英]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;
}
According to the reference, it seems like this is how we're supposed to decorate if
clauses with [[likely]]
or [[unlikely]]
attributes.根据参考资料,这似乎是我们应该用[[likely]]
或[[unlikely]]
属性来装饰if
子句的方式。 It's also supported in C++20 (see here ). C++20 也支持它(参见此处)。
However, I'm running into a warning:但是,我遇到了警告:
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]] { | ^~~~~~~~~~
The codebase is strict about warnings, and this will cause builds to fail.代码库对警告非常严格,这将导致构建失败。 So, am I doing something wrong, or is this a bug?那么,我做错了什么,还是这是一个错误?
g++ version on my macbook:我的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.
There's nothing wrong with your code.你的代码没有问题。 This is due to GCC's implementer overlooking the fact that attributes on compound-statements are a thing .这是由于 GCC 的实现者忽略了复合语句上的属性是一个事实。
[[likely]] if (whatever) {}
means something else entirely - it means that the if
statement itself is "likely", not a branch of it. [[likely]] if (whatever) {}
完全意味着别的东西——这意味着if
语句本身是“可能的”,而不是它的一个分支。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.