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 に答える