【发布时间】:2014-08-19 09:42:54
【问题描述】:
我正在将我的项目从 Visual Studio 06 移动到 2010。在这样做的同时,我在我的代码中观察到了这种行为。我有一个如下所示的 Get 字符串函数:
string GetTheStr()
{
return strSomeStdString;
}
然后还有另一个函数像这样调用上面的get函数:
const char* ptrStr = (char *)GetTheStr().c_str();
ptrStr指向的字符串的值为""
以上代码在 Visual Studio 06 中运行良好,但在 Visual Studio 2010 中运行不正常。
然后我尝试了几个实验:
std::string str = GetTheStr(); // -> value inside str displayed correctly
const char* PtrCStr = str.c_str(); // -> value pointed by PtrCStr displayed correctly
const char* PtrData = str.data(); // -> value pointed by PtrData displayed correctly
const char* ptr = (char *)GetTheStr().c_str(); // -> value pointed by ptr NOT displayed correctly
我想知道为什么最后一行不起作用。 谁能告诉我为什么上述行为发生在 Visual Studio 2010 而不是 Visual Studio 06?
提前致谢:)
【问题讨论】:
-
@MichaelAaronSafyan 这应该是一个答案。
-
不需要
(char *)演员 -
strSomeStdString究竟从何而来?