内存中分配的std :: string在哪里? [英] Where is a std::string allocated in memory?

查看:51
本文介绍了内存中分配的std :: string在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个功能:

void foo() {
   string str = "StackOverflo";
   str.push_back('w');
}

当我们在函数内部声明字符串时,它是存储在堆栈还是堆中?为什么?

When we declare the string inside the function, is it stored on the Stack or Heap? Why?

string foo() {
   string str = "StackOverflo";
   str.push_back('w');
   return str;
}

我们可以返回字符串引用并继续在程序中的其他地方使用吗?

Can we return the string reference and continue using somewhere else in the program?

推荐答案

当我们在函数内部声明String时,它是存储在Stack还是Heap上?

When we declare the String inside the function, is it stored on the Stack or Heap?

字符串对象本身存储在堆栈中,但指向堆上的内存.

The string object itself is stored on the stack but it points to memory that is on the heap.

为什么?

定义该语言,以便将字符串对象存储在堆栈中.字符串构造对象的实现使用堆上的内存.

The language is defined such that the string object is stored on the stack. string's implementation to construct an object uses memory on the heap.

这篇关于内存中分配的std :: string在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆