[[nodiscard]] 属性 ​

什么是 [[nodiscard]] ​

[[nodiscard]] 是 C++17 引入的标准属性,可以加在函数声明或类型定义上。它的作用是告诉编译器:"这个函数的返回值不应该被丢弃。如果调用者调用了这个函数却没有使用返回值,请发出警告。"

这个属性解决的是一个很常见的 bug 来源:调用一个有返回值的函数,却忽略了返回值。比如调用 std::vector::empty() 时忘记用返回值做判断(以为它会清空容器),或者调用一个返回错误码的函数却没有检查错误码。这类 bug 在代码审查中很难发现,因为调用语句本身语法完全合法,编译器默认不会警告。

加上 [[nodiscard]] 后,编译器在发现返回值被丢弃时会生成警告(有些编译器配置下甚至是错误),帮助开发者在编译阶段就发现这类问题。

C++20 进一步增强了这个属性,允许在 [[nodiscard]] 后面加一个字符串字面量来解释"为什么不应该丢弃返回值",让警告信息更有针对性。

基本语法 ​

cpp
// C++17:基本形式
[[nodiscard]] 返回类型 函数名(参数列表);

// C++20:带解释信息的形式
[[nodiscard("解释信息")]] 返回类型 函数名(参数列表);

// 也可以加在类型(struct/class/enum)上
struct [[nodiscard]] ErrorCode {
    int code;
};

[[nodiscard]] 可以应用在:

  • 函数声明上:表示这个函数的返回值不应该被丢弃
  • 类/结构体/枚举声明上:表示以这个类型作为返回值的函数,其返回值都不应该被丢弃

基本示例 ​

cpp
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>

// ============================
// 示例1:在函数上使用 [[nodiscard]]
// ============================

// 分配内存的函数,返回值(指针)不应该被丢弃
// 如果丢弃了返回值,分配的内存就泄漏了
[[nodiscard]] int* allocate_buffer(std::size_t size) {
    return new int[size];
}

// 返回错误码的函数,调用者应该检查返回值
[[nodiscard]] int save_to_file(const std::string& filename, const std::string& data) {
    // 模拟文件保存操作
    if (filename.empty()) {
        return -1;  // 错误:文件名为空
    }
    // ... 实际的保存逻辑 ...
    return 0;  // 成功
}

// ============================
// 示例2:在类型上使用 [[nodiscard]]
// ============================

// 将 [[nodiscard]] 加在类型上
// 所有返回 ErrorInfo 的函数,其返回值都不应该被丢弃
struct [[nodiscard]] ErrorInfo {
    int code;
    std::string message;
};

ErrorInfo do_operation() {
    // 模拟一个可能失败的操作
    return {0, "success"};
}

ErrorInfo validate_input(const std::string& input) {
    if (input.empty()) {
        return {-1, "input is empty"};
    }
    return {0, "ok"};
}

// ============================
// 示例3:C++20 带消息的 [[nodiscard]]
// ============================

// C++20 起可以加解释字符串,让警告更有针对性
[[nodiscard("返回值是新分配的资源,必须手动释放")]]
char* create_string(const char* src) {
    auto len = std::strlen(src) + 1;
    char* buf = new char[len];
    std::memcpy(buf, src, len);
    return buf;
}

[[nodiscard("忽略错误码可能导致静默失败")]]
int connect_to_server(const std::string& host, int port) {
    // 模拟连接操作
    if (host.empty()) return -1;
    return 0;
}

// ============================
// 示例4:标准库中的 [[nodiscard]] 应用
// ============================

void stdlib_example() {
    std::vector<int> v;

    // C++17 起,标准库中很多函数都加了 [[nodiscard]]
    // 比如 std::vector::empty()
    // v.empty();  // 编译器会警告:返回值被丢弃
    // 正确用法:
    if (v.empty()) {
        std::cout << "向量是空的" << std::endl;
    }

    // malloc 在很多实现中也被标记为 [[nodiscard]]
    // std::malloc(100);  // 警告:内存泄漏风险
    // 正确用法:
    void* ptr = std::malloc(100);
    if (ptr) {
        // 使用 ptr ...
        std::free(ptr);
    }
}

int main() {
    // 正确用法:使用返回值
    int* buf = allocate_buffer(100);
    delete[] buf;

    int result = save_to_file("test.txt", "hello");
    if (result != 0) {
        std::cout << "保存失败" << std::endl;
    }

    auto err = do_operation();
    if (err.code != 0) {
        std::cout << "操作失败: " << err.message << std::endl;
    }

    // 以下调用会触发编译器警告(因为返回值被丢弃):
    // allocate_buffer(100);       // 警告:内存泄漏
    // save_to_file("a.txt", ""); // 警告:未检查错误码
    // do_operation();             // 警告:ErrorInfo 类型标记了 nodiscard
    // validate_input("");         // 警告:同上

    // 如果你确实想丢弃返回值(有充分理由),可以显式转换为 void
    (void)save_to_file("log.txt", "debug info");  // 不会触发警告
    // 或者用 std::ignore(需要 #include <tuple>)
    // std::ignore = save_to_file("log.txt", "debug info");

    stdlib_example();

    return 0;
}

标准库中使用 [[nodiscard]] 的函数 ​

C++17 起,标准库中很多函数被标记了 [[nodiscard]],以下是一些常见的:

函数/方法原因
std::vector::empty()容易和 clear() 混淆
std::string::empty()同上
std::async()丢弃返回的 future 会导致同步阻塞
std::launder()返回值是唯一合法的指针
operator new丢弃分配的内存导致泄漏
std::malloc()同上
std::allocator::allocate()同上
std::remove() / std::unique()返回新的逻辑尾迭代器,不使用就无法正确擦除

与其他方式的对比 ​

方式标准支持可移植性适用场景
[[nodiscard]]C++17 标准所有 C++17 编译器推荐使用
__attribute__((warn_unused_result))GCC 扩展仅 GCC/ClangC++17 之前的 GCC 代码
_Check_return_ (SAL)MSVC SAL 注解仅 MSVCWindows 平台特定代码
注释提醒----不可靠,靠人工遵守

适用场景 ​

  • 返回错误码或状态码的函数:调用者必须检查返回值才能知道操作是否成功
  • 分配资源的函数(malloc、new、工厂函数等):丢弃返回值意味着资源泄漏
  • 纯函数(没有副作用的函数):如果不使用返回值,调用就完全没有意义
  • 容易和无返回值函数混淆的函数:比如 empty() 容易被误认为是 clear()
  • 返回值携带关键信息的函数:比如 std::async 返回的 future 对象

常见问题 ​

[[nodiscard]] 是强制性的吗?

不是。编译器只是建议性地发出警告,不是错误。你可以通过 (void)func() 的方式显式丢弃返回值来消除警告。但在代码审查中,如果一个 [[nodiscard]] 函数的返回值被丢弃且没有合理解释,通常会被视为问题。

[[nodiscard]] 加在类型上和加在函数上有什么区别?

加在函数上:只有这一个函数的返回值受 [[nodiscard]] 保护。加在类型上:所有以该类型作为返回值(按值返回)的函数都受保护,不需要每个函数单独加。返回引用或指针不受类型上的 [[nodiscard]] 影响。

如何合法地丢弃 [[nodiscard]] 返回值?

两种常见方式:

  1. (void)func(); —— 显式转换为 void,最通用
  2. std::ignore = func(); —— C++11 起可用,需要 #include <tuple>
  3. [[maybe_unused]] auto result = func(); —— 接收返回值但标记为可能不用

注意事项 ​

  • [[nodiscard]] 只对按值返回有效。如果函数返回引用或指针到 [[nodiscard]] 类型,不会触发警告
  • 构造函数也可以标记 [[nodiscard]](C++20 起明确支持),防止临时对象被创建后立即销毁
  • [[nodiscard]] 不影响运行时行为,只是编译器的诊断提示,零运行时开销
  • 不要滥用 [[nodiscard]]——只在丢弃返回值确实可能导致 bug 或资源泄漏时才使用
  • 在 C++20 中,建议使用带消息字符串的形式 [[nodiscard("原因")]],让警告信息更有帮助

编译器支持情况 ​

编译器[[nodiscard]] (C++17)[[nodiscard("msg")]] (C++20)
GCC7.010.0
Clang3.99.0
MSVC19.11 (VS 2017 15.3)19.26 (VS 2019 16.6)

总结 ​

[[nodiscard]] 是 C++17 提供的一个编译期诊断工具,用来标记"返回值不应该被丢弃"的函数或类型。它帮助编译器在代码中发现忽略返回值的潜在 bug,比如忘记检查错误码、丢弃了分配的资源、把 empty() 当成 clear() 来用等。C++20 增加了消息字符串的支持,让警告更有针对性。在实际开发中,建议给所有返回错误码的函数、分配资源的函数、以及纯函数加上 [[nodiscard]]。如果确实需要丢弃返回值,用 (void) 显式标记意图。