C++ -- where does the system store the returned characters?
#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;
}
Question> We should not return a pointer or reference to a local variab开发者_开发百科le inside a function. So the return variable "aa" is not a local variable inside the function of funA. Then what is it?
Thank you
"aa"
is a string literal, so it has static storage duration. That means it exists from when the program starts to when it ends. It isn't explicitly allocated on the stack or on the free store (heap).
The only temporary object there is the pointer to that string literal, which is returned by value (that means a copy of it is returned).
精彩评论