猿问

分配向量后,它们是否使用堆或堆栈上的内存?

以下所有陈述均正确吗?


vector<Type> vect; //allocates vect on stack and each of the Type (using std::allocator) also will be on the stack


vector<Type> *vect = new vector<Type>; //allocates vect on heap and each of the Type will be allocated on stack


vector<Type*> vect; //vect will be on stack and Type* will be on heap. 

如何Type在一个vector或任何其他STL容器中为内部分配内存?


沧海一幻觉
浏览 741回答 3
3回答

当年话下

vector<Type> vect;将vector在堆栈上分配,即标头信息,但在免费存储(“堆”)上分配元素。vector<Type> *vect = new vector<Type>;在免费商店中分配所有东西。vector<Type*> vect;将vector在堆栈上分配,并在免费存储区上分配一堆指针,但是这些指针的位置由使用方式决定(例如,您可以将元素0指向免费存储区,将元素1指向堆栈)。

慕斯王

假设实际上有一个堆栈和一个堆的实现(标准C ++不需要具有此类东西),则唯一正确的语句是最后一个语句。vector<Type> vect;//allocates vect on stack and each of the Type (using std::allocator) also will be on the stack这是事实,除了最后一部分(Type不会在堆栈上)。想像:&nbsp; void foo(vector<Type>& vec) {&nbsp; &nbsp; &nbsp;// Can't be on stack - how would the stack "expand"&nbsp; &nbsp; &nbsp;// to make the extra space required between main and foo?&nbsp; &nbsp; &nbsp;vec.push_back(Type());&nbsp; }&nbsp; int main() {&nbsp; &nbsp; vector<Type> bar;&nbsp; &nbsp; foo(bar);&nbsp; }同样地:&nbsp;vector<Type> *vect = new vector<Type>; //allocates vect on heap and each of the Type will be allocated on stack除最后一部分外为真,并带有类似的反例:&nbsp; void foo(vector<Type> *vec) {&nbsp; &nbsp; &nbsp;// Can't be on stack - how would the stack "expand"&nbsp; &nbsp; &nbsp;// to make the extra space required between main and foo?&nbsp; &nbsp; &nbsp;vec->push_back(Type());&nbsp; }&nbsp; int main() {&nbsp; &nbsp; vector<Type> *bar = new vector<Type>;&nbsp; &nbsp; foo(bar);&nbsp; }对于:vector<Type*> vect; //vect will be on stack and Type* will be on heap.&nbsp;的确如此,但是请注意,Type*指针将位于堆上,但Type它们指向的实例不必是:&nbsp; int main() {&nbsp; &nbsp; vector<Type*> bar;&nbsp; &nbsp; Type foo;&nbsp; &nbsp; bar.push_back(&foo);&nbsp; }

皈依舞

vector<Type> vect; //allocates vect on stack and each of the Type (using std::allocator) also will be on the stack不,vect将在堆栈上,但是内部用于存储项目的数组将在堆上。这些项目将驻留在该数组中。vector<Type> *vect = new vector<Type>; //allocates vect on heap and each of the Type will be allocated on stack否。与上述相同,除了vector该类也将在堆上。vector<Type*> vect; //vect will be on stack and Type* will be on heap.&nbsp;vect将位于堆栈上,其项(指向的指针Type)将位于堆上,并且您无法确定Type指针所指向的s在哪里。可能在堆栈上,可能在堆上,可能在全局数据中,可能在任何地方(即NULL指针)。顺便说一句,该实现实际上可以将某些矢量(通常为小尺寸)完全存储在堆栈中。我不是知道任何这样的实现,但是可以。
随时随地看视频慕课网APP
我要回答