C++ 基于堆栈的对象分配
C++ stack-based object allocation
在 C++ 中,有两种方法可以声明一个对象。例如:
// The first way
vector<int> *nums = new vector<int>;
// The second way
vector<int> nums;
人们说第一个声明在堆中分配对象,第二个在堆栈中分配对象。我可以想象如果向量对象在堆中它是如何工作的。编译器只会在堆中找到一个空闲块来存储向量。但是,如果随着我不断将新元素推入向量而将对象分配到堆栈上,会发生什么情况?是否有足够的内存space?如果不是,当向量的大小可以改变时,编译器如何在堆栈上找到足够大的内存块来存储向量?
将 vector
对象放入堆栈并不意味着它将其元素放入堆栈。检查文档:
Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it.
在 C++ 中,有两种方法可以声明一个对象。例如:
// The first way
vector<int> *nums = new vector<int>;
// The second way
vector<int> nums;
人们说第一个声明在堆中分配对象,第二个在堆栈中分配对象。我可以想象如果向量对象在堆中它是如何工作的。编译器只会在堆中找到一个空闲块来存储向量。但是,如果随着我不断将新元素推入向量而将对象分配到堆栈上,会发生什么情况?是否有足够的内存space?如果不是,当向量的大小可以改变时,编译器如何在堆栈上找到足够大的内存块来存储向量?
将 vector
对象放入堆栈并不意味着它将其元素放入堆栈。检查文档:
Internally, vectors use a dynamically allocated array to store their elements. This array may need to be reallocated in order to grow in size when new elements are inserted, which implies allocating a new array and moving all elements to it.