3
#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;
}

问题> 我们不应该在函数内部返回指针或对局部变量的引用。所以返回变量“aa”不是 funA 函数内部的局部变量。那这是什么?

谢谢

4

1 回答 1

10

"aa"是字符串文字,因此它具有静态存储持续时间。这意味着它从程序开始到结束都存在。它没有显式分配在堆栈或空闲存储(堆)上。

唯一的临时对象是指向该字符串文字的指针,它按值返回(这意味着返回它的副本)。

于 2011-04-01T16:01:52.663 回答