c++ - 将 std::string 转换为 LPCSTR 时的奇怪行为

标签 c++ string type-conversion stdstring lpcstr

当我在将 std::string 转换为 LPCSTR 时偶然发现一个奇怪的行为时,我正在玩一些字符串。

我写了一个小的测试应用程序来演示:

#include <string>
#include <Windows.h>
#include <iostream>

using namespace std;

int main ()
{
    string stringTest = (string("some text") + " in addition with this other text").c_str(); 
    LPCSTR lpstrTest= stringTest.c_str();
    cout << lpcstrTest << '\n';

    cout << (string("some text") + " in addition with this other text").c_str() << '\n';

    LPCSTR otherLPCSTR= (string("some text") + " in addition with this other text").c_str();
    cout << otherLPSTR;
}

这是输出:

some text in addition with this other text
some text in addition with this other text
îþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþîþ...[more unreadable stuff]...

我只是想知道是什么导致了这种奇怪的行为。

谢谢

最佳答案

LPCSTR otherLPCSTR= (string("some text") + " in addition with this other text").c_str();
cout << otherLPSTR;

部分

 (string("some text") + " in addition with this other text")

创建一个所谓的“临时”对象,它没有名称,并在包含它的语句完成时被破坏。你从中得到 c_str() ,它指向那个临时对象的一些内部存储。您将该 c_str() 分配给 otherLPCSTR 变量。之后,“包含临时字符串的语句”已经完成,因此临时字符串被破坏,otherLPCSTR 指向“无处可去”。

关于c++ - 将 std::string 转换为 LPCSTR 时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11370536/

相关文章:

c++ - 将 std::vector<uint8_t> 转换为 std::string_view

c++ - pnacl-ld : Invalid archive member header magic string

c++ - 优化:昂贵的分支与便宜的比较

c++ - 在 C++ 中的 Windows 中打开命名管道的 ATL 方法是什么?

C# 验证字符串并在 null 或空时显示错误消息的问题

c++ - 用 C++ 编写文本/二进制文件最优雅的方法是什么?

c++ - 需要确保构造函数/析构函数被调用一次。但是 "error: destructor is private"

java - 将字符串转换为日期格式

list - 将 List[Any] 重新解释为 List[Int]

c++ - 将 int 重新解释为 float 的最有效的标准兼容方式