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

我已经编程了一段时间,但主要是 Java 和 C#.我从来没有真正需要自己管理内存.我最近开始用 C++ 编程,我对什么时候应该在堆栈上存储东西以及什么时候将它们存储在堆上有点困惑.

I've been programming for a while but It's been mostly Java and C#. I've never actually had to manage memory on my own. I recently began programming in C++ and I'm a little confused as to when I should store things on the stack and when to store them on the heap.

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

My understanding is that variables which are accessed very frequently should be stored on the stack and objects, rarely used variables, and large data structures should all be stored on the heap. Is this correct or am I incorrect?

推荐答案

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

No, the difference between stack and heap isn't performance. It's lifespan: any local variable inside a function (anything you do not malloc() or new) lives on the stack. It goes away when you return from the function. If you want something to live longer than the function that declared it, you must allocate it on the heap.

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;
}

为了更清楚地了解堆栈是什么,从另一端开始――而不是尝试从高级语言的角度理解堆栈的作用,查找调用堆栈"和调用约定"看看当你调用一个函数时机器真正做了什么.计算机内存只是一系列地址;堆"和栈"是编译器的发明.

For a clearer understanding of what the stack is, come at it from the other end -- rather than try to understand what the stack does in terms of a high level language, look up "call stack" and "calling convention" and see what the machine really does when you call a function. Computer memory is just a series of addresses; "heap" and "stack" are inventions of the compiler.

相关文章