相关疑难解决方法(0)

使用string的c_str()函数的C++奇怪行为

我正在将我的项目从Visual Studio 06移动到2010.在这样做时,我在我的代码中观察到了这种行为.我有一个Get字符串函数,如下所示:

string GetTheStr() 
{ 
        return strSomeStdString; 
} 
Run Code Online (Sandbox Code Playgroud)

然后有另一个函数调用上面的get函数,如下所示:

const char* ptrStr = (char *)GetTheStr().c_str();
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我想知道为什么最后一行不起作用.任何人都可以告诉我为什么上面的行为发生在Visual Studio 2010而不是视觉工作室06?

提前致谢 :)

c++ stdstring

1
推荐指数
2
解决办法
926
查看次数

标签 统计

c++ ×1

stdstring ×1