在C ++中正确的堆栈和堆使用? [英] Proper stack and heap usage in C++?

查看:243
本文介绍了在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()或新)存在于堆栈。当你从函数返回时,它会消失。如果你想要的东西比声明它的函数寿命更长,你必须分配它在堆上。

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

为了更清楚地了解堆栈是什么,结束 - 而不是试图了解堆栈在高级语言方面的作用,查找调用堆栈和调用约定,看看当调用函数时,机器真正做什么。计算机内存只是一系列地址; heap和stack是编译器的发明。

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.

这篇关于在C ++中正确的堆栈和堆使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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