通过


警告 C6284

在对“*function*”的调用中需要字符串时作为参数传递的对象

备注

此警告指示该格式说明符与在 printf 样式函数中使用的类型之间存在不匹配问题。 格式说明符是 C 样式字符串类型(例如 %s%ws),参数是类/结构/联合类型。 除了可能出现不正确的输出,此缺陷还可能导致故障。

此缺陷通常是由于忘记转换对象字符串类型(例如 std::stringCComBSTRbstr_t 转换为 printf 样式函数所需的 C 样式字符串)。 如果是这样,修复程序是将适当的转换添加到类型。 需要进行该转换,因为 printf 样式函数的可变参数是非类型化的,因此不会发生自动转换。

代码分析名称:OBJECT_AS_STRING_ARGUMENT_TO_FORMAT_FUNCTION

示例

以下示例生成 C6284:

#include <atlbase.h>
#include <string>

void f()
{
  char buff[50];
  CComBSTR bstrValue{"Hello"};
  std::string str{"World"};

  // Oops, %ws and %s require C-style strings but CComBSTR and std::strings are being passed instead
  sprintf(buff, "%ws %s", bstrValue, str);
}

通过添加相应的转换来修复警告:

#include <atlbase.h>
#include <string>

void f()
{
  char buff[50];
  CComBSTR bstrValue{"Hello"};
  std::string str{"World"};

  // Fixed by adding a static_cast to the CComBSTR and calling c_str() on the std::string
  sprintf(buff, "%ws %s", static_cast<wchar_t*>(bstrValue), str.c_str());
}

另请参阅

static_cast 运算符
sprintf_s, _sprintf_s_l, swprintf_s, _swprintf_s_l
C4477
C4840