首页 > 解决方案 > 警告 C6031 返回值在宏扩展中被忽略

问题描述

我正在使用以下代码格式化HRESULT消息并将消息写入文件,仅当HRESULT出现错误时。

代码编译并且工作正常,除了我收到以下编译器警告

警告 C6031 忽略返回值:'wcsrchr'。

我不想禁用警告但要解决它,但我无法弄清楚如何?这是一个最小的可编译代码:

// compile with: /Wall
#include <Windows.h>
#include <cwchar>       // std::wcsrchr
#include <comdef.h>     // _com_error
#include <iostream>     // std::cin

// Show only file name instead of full path wide version
#define __FILENAME__ (std::wcsrchr(TEXT(__FILE__), L'\\') ? std::wcsrchr(TEXT(__FILE__), L'\\') + 1 : TEXT(__FILE__))

// Writes a sprintf-formatted string to the logging file.
#define TRACE(...) DebugLogTrace(__VA_ARGS__)

// Log HRESULTs if failed.
#define LOG_IF_FAILED(file_name, line, hr) if constexpr (FAILED(hr)) \
    { TRACE((TEXT("%s %i %s"), file_name, line, _com_error(hr).ErrorMessage())); }

// Writes a sprintf-formatted string to the logging file.
void DebugLogTrace(PCTSTR format_string, ...) noexcept
{
    // implementation not important
}

int main()
{
      // generate example failure
      LOG_IF_FAILED(__FILENAME__, __LINE__, E_FAIL);

      std::cin.get();
      return 0;
}

E_FAIL错误代码的示例文件输出:

7:50:11 未指定的错误

标签: c++error-handlingmacroscompiler-warnings

解决方案


通过更改,我能够使警告消失:

#define LOG_IF_FAILED(file_name, line, hr) if constexpr (FAILED(hr)) \
    { TRACE((TEXT("%s %i %s"), file_name, line, _com_error(hr).ErrorMessage())); }

#define LOG_IF_FAILED(file_name, line, hr) if constexpr (FAILED(hr)) \
    { TRACE(TEXT("%s %i %s"), file_name, line, _com_error(hr).ErrorMessage()); }

即:{ TRACE((..., ..., ..., ...)); }{ TRACE(..., ..., ..., ...); }

但我不得不承认,我不知道删除多余的括号是否还有其他一些意想不到的结果。


推荐阅读