【问题标题】:C++ -- where does the system store the returned characters?C++——系统在哪里存储返回的字符?
【发布时间】:2011-04-01 16:00:55
【问题描述】:
#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 函数内部的局部变量。那是什么?

谢谢

【问题讨论】:

  • 没有它存储的地方只是返回发送到输出屏幕

标签: c++ static object-lifetime


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2010-11-17
    • 2018-11-09
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    相关资源
    最近更新 更多