编译器警告(等级 1)C4834

放弃具有“nodiscard”属性的函数的返回值

注解

从 C++17 标准开始,[[nodiscard]] 属性指定函数的返回值不应被放弃。 如果调用方放弃返回值,编译器会生成警告 C4834。 尽管此属性是在 C++17 中引入的,但编译器仍遵循此属性,并在使用 /std:c++14 和更高版本时生成与其相关的警告。

若要解决此警告,请考虑代码不使用返回值的原因。 你对函数的使用可能与其意图不符。 你可以通过将值赋给 std::ignore 或将其强制转换为 void 来规避该警告(如果有益放弃该值)。
在 C++ 11 及更高版本中,向 std::ignore 赋值优先于强制转换为 void 的操作,因为这会使你的意图更加明确,并且不会触发警告 C26457(如果已在代码分析设置中启用)。

Visual Studio 2017 版本 15.3 中引入了此警告作为 3 级警告。 Visual Studio 2017 版本 15.7 中将其更改为 1 级警告。 在 Visual Studio 2017 版本 15.3 之前的编译器版本中编译时没有警告的代码现在可能生成 C4834。 若要了解如何禁用特定编译器版本或更高版本中引入的警告,请参阅由编译器版本引发的编译器警告

在不更改代码的情况下关闭警告

可以使用 warning 杂注 #pragma warning(suppress : 4834) 关闭特定代码行的警告。 还可以使用警告杂注 #pragma warning(disable : 4834) 关闭文件中的警告。 可以使用 /wd4834 命令行选项在命令行版本中全局关闭警告。

若要关闭 Visual Studio IDE 中整个项目的警告,请执行以下操作:

  1. 打开项目的“属性页”对话框。 有关如何使用“属性页”对话框的信息,请参阅属性页
  2. 选择“配置属性”>“C/C++”>“高级”页
  3. 编辑“禁用特定警告”属性以添加 4834。 选择“确定”以应用更改

示例

此示例会生成 C4834,并展示 4 种修复方法:

// C4834.cpp
// compile using: cl /EHsc /std:c++17
#include <iostream>

[[nodiscard]]
int square_of(int i) { return i * i; }

int main()
{
    square_of(42); // warning C4834: discarding return value of function with 'nodiscard' attribute
    // If ignoring the [[nodiscard] attribute is unintentional, make use of the return value as intended:
    // For example:
    std::cout << "square_of(42) = " << square_of(42) << "\n"; // Ok
    // Or:
    int result = square_of(43); // Ok
    std::cout << "square_of(43) = " << result << "\n"; 

    // If ignoring the [[nodiscard]] attribute value is intentional, you have two options:
    // Preferrably, assign the return value to std::ignore:
    std::ignore = square_of(42); // Ok, C++11 and higher
    // Alternatively, you can cast the return value to void. 
    // The intent may be less clear to other developers.
    (void) square_of(42); // May produce warning C26457
    return 0;
}