次の方法で共有


警告 C6284

'*function*' の呼び出しで文字列が必要な場合にパラメーターとして渡されるオブジェクト

解説

この警告は、書式指定子と -style 関数で使用されている型の間に printf不一致があることを示します。 書式指定子は C スタイルの文字列型 (or %wsなど%s) で、引数はクラス/構造体/共用体型です。 この欠陥が原因で、出力が正しくなくなる可能性に加えて、クラッシュする可能性もあります。

この問題は、多くの場合、-style 関数が期待するオブジェクト文字列型 (std::stringCComBSTRまたは bstr_t C スタイル文字列) への変換をprintf忘れたために発生します。 その場合、修正は型に適切な変換を追加します。 -style 関数への printf可変引数パラメーターは型指定されていないため、自動変換は行われないため、変換が必要です。

コード分析名: OBJECT_AS_STRING_ARGUMENT_TO_FORMAT_FUNCTION

#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