用于自动引用的__attribute__((未使用))

gcc and __attribute__((unused)) for auto references

本文关键字:attribute 未使用 引用 用于      更新时间:2023-10-16

使用gcc(已测试5.4.0和6.1.1)和-Wall,会对auto_ref的未使用变量发出警告,但不会对其他变量发出警告。Clang不发出任何警告。这对auto来说是不同的吗?要使用变量,为什么?

int main() {
    int __attribute__((unused)) int_var_unused = 42;
    int int_var = 42;
    int& __attribute__((unused)) int_ref = int_var;
    auto __attribute__((unused)) auto_var_unused = 42;
    auto auto_var = 42;
    auto& __attribute__((unused)) auto_ref = auto_var;
    return 0;
}

不确定这是否是GCC中的错误,但它是这样工作的

__attribute__((unused)) auto& auto_ref = auto_var;

和像这样

auto& auto_ref __attribute__((unused)) = auto_var;

我猜这个属性从来没有打算放在类型声明和名称之间。在文档中,我主要将第二个版本作为示例。