当我在将 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/