c++ - 为什么将 std::string 传递给 CString.Format() 有时只会崩溃?

标签 c++ c++11 c-strings stdstring

使用 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/

相关文章:

c++ - 在 C++ dll 中删除指针时出错

c++ - 从容器中提取段的函数

c++ - 如何用字符串文字初始化 const char []

c - 将枚举与字符串相关联的正确方法

c - 我的 curl 结果未读取为字符串

c++ - std::thread 中的 Visual Studio 2012 错误 C2248

javascript - Wt(诙谐)。对 Javascript 实现不起作用一无所知

C++ 内存调试器?

c++ - 现在如何在 C++11 中编写 for 循环?

c++ - 如果存储原始引用的类超出范围,捕获成员引用是否安全?