c++ - 在 C++ 中正确使用堆栈和堆?

标签 c++ memory-management stack heap-memory c++-faq

我已经编程了一段时间,但主要是 Java 和 C#。我从来没有真正需要自己管理内存。我最近开始使用 C++ 进行编程,对于何时应该将内容存储在堆栈中以及何时将它们存储在堆中感到有些困惑。

我的理解是,经常访问的变量应该存放在栈和对象上,很少使用的变量,大数据结构都应该存放在堆上。这是正确的还是我的错误?

最佳答案

不,堆栈和堆之间的区别不在于性能。它的生命周期:函数内的任何局部变量(任何你不使用 malloc() 或 new 的变量)都存在于堆栈中。当您从函数返回时,它会消失。如果你想让某个东西比声明它的函数生命周期更长,你必须在堆上分配它。

class Thingy;

Thingy* foo( ) 
{
  int a; // this int lives on the stack
  Thingy B; // this thingy lives on the stack and will be deleted when we return from foo
  Thingy *pointerToB = &B; // this points to an address on the stack
  Thingy *pointerToC = new Thingy(); // this makes a Thingy on the heap.
                                     // pointerToC contains its address.

  // this is safe: C lives on the heap and outlives foo().
  // Whoever you pass this to must remember to delete it!
  return pointerToC;

  // this is NOT SAFE: B lives on the stack and will be deleted when foo() returns. 
  // whoever uses this returned pointer will probably cause a crash!
  return pointerToB;
}

为了更清楚地了解堆栈是什么,请从另一端了解堆栈——不要试图从高级语言的角度理解堆栈的作用,而是查找“调用堆栈”和“调用约定”当你调用一个函数时,看看机器到底做了什么。计算机内存只是一系列地址; “堆”和“栈”是编译器的发明。

关于c++ - 在 C++ 中正确使用堆栈和堆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/599308/

相关文章:

c++ - 将设置位移动到 64 位整数的末尾

c++ - 减少内存分配 C++

c - 动态字符数组 - 堆栈

java - StackOverflowError 什么时候发生?

c++ - 表达式 _BLOCK_TYPE_IS_VALID(pHead->nBlockUse) 错误

c++ - 将 IP 地址从 sockaddr_in6 转换为 in_addr

c++ - 在流行的Coin-Change动态编程问题中遍历状态的正确顺序是什么?

c++ - 从派生类引用基类成员

c - 通过将 char 指针设置为 NULL 来模拟 calloc 的失败

c++ - 指向 void 的指针变成智能指针