【发布时间】:2010-10-22 04:19:00
【问题描述】:
调用string::c_str()返回的指针指向哪里?在下面的代码 sn-p 中,我认为我会得到一个分段错误,但它给了我正确的输出。如果 string::c_str() 返回的指针指向字符串对象内部的一个内部位置,那么当函数返回并且对象析构函数被调用时,我应该得到一个无效的内存访问。
#include <iostream>
#include <string>
using namespace std;
const char* func()
{
string str("test");
return str.c_str();
}
int main()
{
const char* p = func();
cout << p << endl;
return 0;
}
Output: test
Compiler: g++ 4.3.3
Platform: ubuntu 2.6.28-19
【问题讨论】: