使用 CString.Format()
,我向它传递一个 std::map
,它在给定时返回一个 std::string
一个 int
。
所以:
CString cStr;
cStr.Format("%s", IntToStdStringMap[1]);
其中 IntToStdStringMap[1]
返回一些字符串,我们会说“Hello, World!”。问题是这似乎并不是每次都崩溃。最终,我会收到访问冲突。
为什么会这样?
请记住,将代码更改为以下内容:
CString cStr;
cStr.Format("%s", IntToStdStringMap[1].c_str());
缓解了这个问题。
有什么想法吗?
最佳答案
将 std::string
传递给 CString::Format
是不正确的。来自 https://msdn.microsoft.com/en-us/library/aa314327(v=vs.60).aspx :
The format has the same form and function as the format argument for the printf function.
这意味着,当格式说明符是 %s
时,预期的参数类型是 char const*
,而不是 std::string
。
因此,使用
cStr.Format("%s", IntToStdStringMap[1]);
是导致未定义行为的原因,而
的行为cStr.Format("%s", IntToStdStringMap[1].c_str());
定义明确。
关于c++ - 为什么将 std::string 传递给 CString.Format() 有时只会崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44890447/