gcc中的C++11样式[[unused]]属性
C++11-style [[unused]] attribute in gcc?
在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。
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- C++概念:如何使用'concept'检查模板化结构的属性?
- 子目录是否继承属性,例如add_definitions,include_directories和父Cmakelist.t
- 通过指向指针数组的指针访问子类的属性
- MSVC是否支持C++11样式的属性而不是__declspec
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 类的C++属性似乎已重新初始化
- Qt Quick-如何仅从c++代码与qml属性交互
- 用概念检查属性的类型
- C++如何将同一类的实例作为属性
- 按多个属性排序
- 主函数参数的属性
- "perf_event_attr"结构的"read_format"属性的选项到底是什么?
- C++删除未使用的类属性会导致 std::logic_error
- 无法使用 SWIG 在 Python 中实例化C++类(获取属性错误)
- 使用内存地址访问结构的属性值
- C++调用具有 *this 属性的单个帮助程序函数
- C++ 在堆栈中包含多态属性的类对象存储
- GCC:变量属性"__unused__"与仅"unused"
- gcc中的C++11样式[[unused]]属性