q09*_*987 3 c++ static object-lifetime
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
const char* funA()
{
return "aa"; // where does system to store this temporary variable?
}
// this is not an valid function
const char* funB()
{
string str("bb");
return str.c_str();
}
int _tmain(int argc, _TCHAR* argv[])
{
cout << funA() << endl;
cout << funB() << endl; // invalid
return 0;
}
Run Code Online (Sandbox Code Playgroud)
问题>我们不应该返回指向函数内局部变量的指针或引用.因此返回变量"aa"不是funA函数内的局部变量.那这是什么?
谢谢
Jam*_*lis 10
"aa"
是字符串文字,因此它具有静态存储持续时间.这意味着它从程序开始到结束时都存在.它未在堆栈或免费存储(堆)上显式分配.
唯一的临时对象是指向该字符串文字的指针,该值由value返回(表示返回它的副本).