Proper stack and heap usage in C++?(在 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.
这篇关于在 C++ 中正确使用堆栈和堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中正确使用堆栈和堆?
基础教程推荐
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01