将 std::string 转换为 LPCSTR 时的奇怪行为 [英] Weird behavior while converting a std::string to a LPCSTR
问题描述
当我在将 std::string
转换为 LPCSTR
时偶然发现一个奇怪的行为时,我正在玩一些字符串.
I was playing with some strings when I stumbled upon a weird behavior while converting a std::string
to a LPCSTR
.
我编写了一个小型测试应用程序来演示:
I have written a small test application to demonstrate :
#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]...
我只是想知道是什么导致了这种奇怪的行为.
I am simply wondering what is causing this strange behavior.
谢谢
推荐答案
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指向nowhere".
creates a so-called "temporary" object, which has no name and gets destructed when the statement that contains it finishes. You get the c_str() from that, which points to some internal storage of that temporary object. You assign that c_str() to the otherLPCSTR variable. After that, "the statment that contains the temporary string" has finished, so the temporary string gets destructed, and the otherLPCSTR points "nowhere".
这篇关于将 std::string 转换为 LPCSTR 时的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!