【发布时间】:2012-07-07 09:42:21
【问题描述】:
当我在将 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]...
我只是想知道是什么导致了这种奇怪的行为。
谢谢
【问题讨论】:
-
看起来你用添加创建了一个临时对象,然后在它上面调用
c_str()并使用那个指针,当临时对象消失时它就失效了。 -
@BoBTFish 正确,具体指
stringTest的初始化。 -
哈哈,那么简单的问题。一直认为
c_str()返回的是一个值,而不是一个指针。谢谢。
标签: c++ string type-conversion stdstring lpcstr