【问题标题】:[[maybe_unused]] in if statement doesn't seem to work in GCCif 语句中的 [[maybe_unused]] 似乎在 GCC 中不起作用
【发布时间】:2019-07-31 00:29:39
【问题描述】:

[[maybe_unused]] 的重点是它告诉编译器不要警告未使用的变量,对吧?那么为什么 GCC 会在此处警告 ui 未使用?

#include <iostream>
#include <vector>

#define NDEBUG
#include <cassert>

int main()
{   
  std::vector<int> numbers = {1,2,3};

  if ([[maybe_unused]] auto  ui = static_cast<unsigned int>(numbers.size()))
  {
    assert(ui);
    std::cout << "ok" << std::endl;
  }
}

我做错了吗?这是编译器的错误吗?

(顺便说一句:在 Wandbox 上尝试这个,Clang 似乎没有警告 ui 未使用,无论 [[maybe_unused]] 是否存在)。

(此外:MSVC 也不会警告 ui 未使用,即使 [[maybe_unused]] 不存在)。

【问题讨论】:

    标签: c++ gcc c++17 gcc-warning


    【解决方案1】:

    对我来说似乎是一个编译器错误。该属性可以应用于任何变量声明,这就是变量声明。

    归档91304

    【讨论】:

    • 来自票证:Martin Sebor 指出if (int i [[maybe_unused]] = f()) { } 确实有效。
    • 当然可以。不过,它完成了我最初想做的事情,所以我认为这值得一提。
    • 我还注意到 Clang 和 MSVC 毫无怨言地接受 if (int i [[maybe_unused]] = f()) { },所以这个技巧是跨平台的。
    猜你喜欢
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 2021-11-03
    • 2017-05-22
    相关资源
    最近更新 更多