gpt4 book ai didi

c++ - 为什么 C++20 中的 [[likely]] 属性会在此处引发警告?

转载 作者:行者123 更新时间:2023-12-01 14:15:52 26 4
gpt4 key购买 nike

#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;
}

Demo

根据引用资料,这似乎是我们应该如何装饰 if条款与 [[likely]][[unlikely]]属性。 C++20 也支持它(见 here)。

但是,我遇到了警告:

main.cpp:在函数“int foo(int, int)”中:
main.cpp:5:15: 警告:语句开头的属性被忽略 [-Wattributes]
5 | if(a < b) [[可能]] {
| ^~~~~~~~~~

代码库对警告很严格,这会导致构建失败。那么,我做错了什么,还是这是一个错误?

我的 macbook 上的 g++ 版本:

g++-9 (Homebrew GCC 9.3.0_1) 9.3.0
版权所有 (C) 2019 Free Software Foundation, Inc.
这是免费软件;请参阅复制条件的来源。没有
保修单;甚至不是为了特定目的的适销性或适合性。

最佳答案

你的代码没有任何问题。这是由于 GCC 的实现者 overlooking the fact that attributes on compound-statements are a thing .
[[likely]] if (whatever) {}完全意味着别的东西 - 这意味着 if语句本身是“可能的”,而不是它的一个分支。

关于c++ - 为什么 C++20 中的 [[likely]] 属性会在此处引发警告?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62398252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com