編譯程式警告 (層級 1) C4834

捨棄具有 『nodiscard』 屬性之函式的傳回值

備註

從 C++17 Standard 開始, [[nodiscard]] 屬性會指定函式的傳回值不會被捨棄。 如果呼叫端捨棄傳回值,編譯程式會產生警告 C4834。 雖然此屬性是在 C++17 中引進的,但編譯程式會遵守此屬性,並在使用 /std:c++14 和更新版本時產生與其相關的警告。

若要解決此警告,請考慮您的程式代碼為何不使用傳回值。 您的函式使用可能不符合其意圖。 您可以藉由將值指派給 std::ignore ,或在捨棄值是刻意的時,將它 void 轉換成 ,來規避警告。
在 C++11 和更新版本中,慣用指派至 std::ignorevoid ,因為它可讓您的意圖更清楚,而且如果在程式碼分析設定中啟用警告 C26457,則不會觸發 警告 C26457

此警告是在Visual Studio 2017 15.3版中引進的,做為層級3警告。 它已變更為 Visual Studio 2017 15.7 版中的層級 1 警告。 在 Visual Studio 2017 15.3 版之前,在編譯程式版本中在沒有警告的情況下編譯的程式代碼現在可以產生 C4834。 如需如何停用特定編譯程式版本或更新版本中導入的警告的資訊,請參閱 編譯程式版本的編譯程式警告。

關閉警告而不變更程序代碼

您可以使用 pragma ,#pragma warning(suppress : 4834)關閉特定程式代碼warning行的警告。 您也可以使用 warning pragma , #pragma warning(disable : 4834)關閉檔案內的警告。 您可以使用命令列選項,在命令行組建 /wd4834 中全域關閉警告。

若要關閉 Visual Studio IDE 中整個專案的警告:

  1. 開啟專案的 [ 屬性頁] 對話框。 如需如何使用 [屬性頁] 對話框的資訊,請參閱 屬性頁
  2. 選取 [組態屬性>C/C++>進階] 頁面。
  3. 編輯停用 特定警告 屬性以新增 4834。 選擇 [ 確定 ] 以套用變更。

範例

此範例會產生 C4834,並示範四種方式來修正此問題:

// 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;
}