gcc中的C++11样式[[unused]]属性

C++11-style [[unused]] attribute in gcc?

本文关键字:unused 属性 样式 中的 C++11 gcc      更新时间:2023-10-16

在gcc/g++4.9下,我可以写:

int x __attribute__((unused)) = f();

以指示x是故意未使用的。

用C++11[[]]属性表示法有可能做到这一点吗?

我试过了:

int x [[unused]] = f();

但它不起作用。

(是的,我知道这是一个实现定义的属性。(

C++17中有[[maybe_unused]]属性。它在GCC 7中实现,请参阅GCC中的C++标准支持。

P0212R1提案示例:

[[maybe_unused]] void f([[maybe_unused]] bool thing1,
                        [[maybe_unused]] bool thing2) {
    [[maybe_unused]] bool b = thing1 && thing2;
    assert(b);
}

是,使用[[gnu::unused]]

如前所述,unused不是标准指定的标准属性的一部分。

该标准允许实现定义的属性(如__attribute____declspec(与新语法一起使用。如果编译器无法识别某个属性(例如在MSVC上编译时为gcc属性(,它将被忽略。(可能有警告(

对于gcc,您可以使用gnu前缀和C++11属性语法:[[gnu::unused]]而不是__attribute__((unused)),这也应该适用于其他gcc属性。

没有gnu前缀的示例

带有gnu前缀的示例

您所指的东西被称为属性说明符。这是对各种依赖于平台的说明符进行标准化的尝试:

  • GCC情况下的__attribute__/ICC(Linux(
  • MSVC上的__declspec/ICC(Windows(

正如您在所附的文档链接中看到的,C++11中唯一支持的说明符是:

  • [[noreturn]]
  • [[carries_dependency]]

在C++14中:

  • [[deprecated]](也支持为:[[deprecated("reason")]](

C++17是引入所需功能的版本:

  • [[maybe_unused]](cppreference.com(

链接示例:

#include <cassert>
 
[[maybe_unused]] void f([[maybe_unused]] bool thing1,
                        [[maybe_unused]] bool thing2)
{
    [[maybe_unused]] bool b = thing1 && thing2;
    assert(b); // in release mode, assert is compiled out, and b is unused
               // no warning because it is declared [[maybe_unused]]
} // parameters thing1 and thing2 are not used, no warning

所以答案是:不,这是不可能的,只使用C++11功能-以可移植的方式获得这一功能所需的C++版本是C++17。


如果您对可移植解决方案不感兴趣,可能有一种方法。C++标准不限制此列表:

C++标准只定义了以下属性所有其他属性都是特定于实现的

各种编译器可以支持一些非标准说明符。例如,您可以阅读此页面以了解Clang支持的内容:

  • [[gnu::unused]]

也许您的GCC版本也支持这个说明符。此页面包含一个错误报告,该报告引用了通用属性支持。还提到了CCD_ 17。