C6284

警告 C6284:传递了对象参数“%d”,而对 <function> 的调用需要字符串参数。

此警告意味着,格式字符串指定需要字符串,例如,为 printf 或 scanf 指定 %s,但所传递的是 C++ 对象。

此缺陷可能产生错误的输出或系统崩溃。

通常,如果向 C printf 样式的调用传递了实现某个字符串类型的 C++ 对象,例如 std::string、CComBSTR 或 bstr_t,将报告此消息。 如果定义了正确的强制转换运算符,当需要 C 字符串时,C++ 字符串对象通常可以透明地使用,具体取决于 C++ 类的实现;然而,因为 printf 样式的函数的参数基本上是非类型化的,所以不会发生转换成字符串的情况。

可能适合将 static_cast 运算符插入到适当的字符串类型(例如 char * 或 TCHAR *)中,或者适合对 std::string 的实例调用返回字符串的成员函数,如 c_str(),这取决于具体的对象。

示例

在下面的代码中,因为向 sprintf 函数传递了 CComBSTR,所以会生成此警告:

#include <atlbase.h>
#include <stdlib.h>

void f()
{
  char buff[50];
  CComBSTR bstrValue("Bye");
 
  sprintf(buff,"%ws",bstrValue); 
}

下面的代码使用静态强制转换来更正此警告:

#include <atlbase.h>
#include <stdlib.h>

void f()
{
  char buff[50];
  CComBSTR bstrValue("Bye");
  
  sprintf_s(buff,50,"%ws",static_cast<wchar_t *>(bstrValue));
}

请参见

参考

static_cast Operator

sprintf_s, _sprintf_s_l, swprintf_s, _swprintf_s_l