下面这些说法都是正确的吗?

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. 

内存如何在一个向量或任何其他STL容器的类型内部分配?


假设一个实现实际上有一个堆栈和一个堆(标准c++不要求有这样的东西),唯一正确的语句是最后一条。

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

这是正确的,除了最后一部分(Type不会在堆栈上)。想象一下:

  void foo(vector<Type>& vec) {
     // Can't be on stack - how would the stack "expand"
     // to make the extra space required between main and foo?
     vec.push_back(Type());
  }

  int main() {
    vector<Type> bar;
    foo(bar);
  }

同样的:

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

除了最后一部分是正确的,还有一个类似的反例:

  void foo(vector<Type> *vec) {
     // Can't be on stack - how would the stack "expand"
     // to make the extra space required between main and foo?
     vec->push_back(Type());
  }

  int main() {
    vector<Type> *bar = new vector<Type>;
    foo(bar);
  }

For:

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

这是正确的,但注意这里的Type*指针将在堆上,但它们所指向的Type实例不需要:

  int main() {
    vector<Type*> bar;
    Type foo;
    bar.push_back(&foo);
  }

向量类型> < vect;//在堆栈上分配vect,并且每个Type(使用std::allocator)也将在堆栈上

不,vect将在堆栈上,但它在内部用于存储项的数组将在堆上。项目将驻留在该数组中。

vector<Type> * vector = new vector<Type>;//在堆上分配vect,每个Type将被分配到堆栈上

不。和上面一样,除了vector类也在堆上。

向量<类型* > vect;// vector对象在栈上,Type*在堆上。

vect将在堆栈上,它的项(指向Type的指针)将在堆上,并且你无法知道指针指向的类型将在哪里。可能在堆栈上,可能在堆上,可能在全局数据中,可能不在任何地方。空指针)。

顺便说一下,这个实现实际上可以将一些向量(通常是小尺寸的)完全存储在堆栈上。我不知道有任何这样的实现,但它可以。


vector<Type> vect;

将在堆栈上分配向量,即头信息,但在自由存储(“堆”)上分配元素。

vector<Type> *vect = new vector<Type>;

分配免费存储中的所有内容。

vector<Type*> vect;

将在堆栈上分配向量,并在自由存储区上分配一堆指针,但这些指针的位置取决于您如何使用它们(例如,您可以将元素0指向自由存储区,将元素1指向堆栈)。


只有这句话是正确的:

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

类型*指针存储在堆上,因为指针的数量可以动态变化。

在本例中,Vect是在堆栈上分配的,因为您将它定义为一个本地堆栈变量。


Vector有一个内部分配器,负责从堆中为Vector元素分配/释放内存。所以无论你如何创建一个向量,它的元素总是分配在堆上。至于向量的元数据,这取决于创建它的方式。