C++17 属性标记:fallthrough、nodiscard 与 maybe_unused

2026年7月13日 Crystal-Sky 2 min read C++C++17基础语法属性fallthroughnodiscardmaybe_unused

属性标记简介

C++ 属性使用:

[[attribute]]

向编译器提供额外信息。它通常不会改变程序逻辑,而是帮助编译器进行检查和优化。

C++17 常用属性:

  • [[fallthrough]]
  • [[nodiscard]]
  • [[maybe_unused]]

[[fallthrough]]

作用

用于 switch 中,表示当前 case 故意继续执行下一个 case。

普通情况:

switch(x)
{
case 1:
    cout<<"one";

case 2:
    cout<<"two";
}

如果 x 为 1,会继续执行 case 2。

为了避免编译器认为忘记写 break:

switch(x)
{
case 1:
    cout<<"one";
    [[fallthrough]];

case 2:
    cout<<"two";
    break;
}

[[nodiscard]]

作用

表示函数返回值或者对象结果不应该被忽略。

例如:

[[nodiscard]]
int getValue()
{
    return 100;
}

int main()
{
    getValue(); // 编译器警告
}

常用于:

  • 错误码;
  • 状态检查;
  • 资源创建函数。

例如:

[[nodiscard]]
bool openFile();

调用者应该检查:

if(openFile())
{
    // success
}

修饰类型

也可以修饰类型:

struct [[nodiscard]] Error
{
    int code;
};

如果:

Error getError();

getError();

同样会产生提醒。

[[maybe_unused]]

作用

告诉编译器:

这个变量、参数或者函数可能不会被使用。

例如:

void debug([[maybe_unused]] int value)
{

}

不会产生 unused parameter 警告。

也可以用于变量:

int main()
{
    [[maybe_unused]]
    int version = 17;
}

三个属性对比

属性用途作用
fallthroughswitch允许 case 穿透
nodiscard返回值/类型提醒不要忽略结果
maybe_unused变量/参数允许未使用

综合示例

#include <iostream>
using namespace std;

[[nodiscard]]
bool connect()
{
    return true;
}

void test([[maybe_unused]] int mode)
{
}

int main()
{
    int x = 1;

    switch(x)
    {
    case 1:
        cout<<"start";
        [[fallthrough]];

    case 2:
        cout<<"run";
        break;
    }

    connect(); // 提醒返回值未使用

    return 0;
}

常见错误

误解 nodiscard

nodiscard 不会阻止程序运行,只产生编译器提醒。

fallthrough 放置错误

错误:

case 1:
    [[fallthrough]];
    cout<<"hello";

正确:

case 1:
    cout<<"hello";
    [[fallthrough]];

case 2:

总结