我使用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:
这意味着,当格式说明符为%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/