开发者

C++ -- where does the system store the returned characters?

开发者 https://www.devze.com 2023-02-21 03:04 出处:网络
#include \"stdafx.h\" #include <iostream> #include <string> using namespace std; const char* funA()
#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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号