0

std::string当我在将 a 转换为 a时偶然发现一个奇怪的行为时,我正在玩一些字符串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]...

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

谢谢

4

3 回答 3

2
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 变量。之后,“包含临时字符串的语句”已经完成,因此临时字符串被破坏,而其他LPCSTR 指向“无处”。

于 2012-07-06T22:48:29.627 回答
0

由表达式创建的临时对象将一直存在,直到完整表达式的评估完成为止。一旦评估了完整的表达式,它的所有临时变量都会自动销毁。

这就是发生的事情

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

在此语句之后,临时对象立即被销毁,并otherLPCSTR最终指向死内存。

在第一种情况下,这stringTest不是暂时的。它一直存在到 的末尾main,这意味着该lpstrTest指针仍然有效。

在第二种情况下,临时std::string对象在它还活着的时候立即用于输出。

只有在第三种情况下,您才试图存储一个指针,如上所述,该指针会失效。

于 2012-07-06T22:48:57.850 回答
0

返回的指针c_str()只有在其字符串对象存在时才有效。

// A copy of a temporary string is made here. The temporary is destructed 
// but stringTest stays in scope until the end of main
string stringTest = (string("some text") + " in addition with this other text").c_str();

LPCSTR lpstrTest= stringTest.c_str();
cout << lpcstrTest << '\n';

// the temporary is in scope until the end of the full expression, so this is fine.

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

// But this isn't. At the end of the line, the temporary string object is long gone.
// otherLPCSTR now points to deallocated memory.
LPCSTR otherLPCSTR= (string("some text") + " in addition with this other text").c_str();

// And here you're accessing that memory.
cout << otherLPSTR;
于 2012-07-06T22:51:32.733 回答