3 回答

TA貢獻1890條經驗 獲得超9個贊
vector<Type> vect;
將vector在堆棧上分配,即標頭信息,但在免費存儲(“堆”)上分配元素。
vector<Type> *vect = new vector<Type>;
在免費商店中分配所有東西。
vector<Type*> vect;
將vector在堆棧上分配,并在免費存儲區上分配一堆指針,但是這些指針的位置由使用方式決定(例如,您可以將元素0指向免費存儲區,將元素1指向堆棧)。

TA貢獻1864條經驗 獲得超2個贊
假設實際上有一個堆棧和一個堆的實現(標準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);
}
對于:
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);
}

TA貢獻1851條經驗 獲得超3個贊
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.
vect將位于堆棧上,其項(指向的指針Type)將位于堆上,并且您無法確定Type指針所指向的s在哪里??赡茉诙褩I?,可能在堆上,可能在全局數據中,可能在任何地方(即NULL指針)。
順便說一句,該實現實際上可以將某些矢量(通常為小尺寸)完全存儲在堆棧中。我不是知道任何這樣的實現,但是可以。
- 3 回答
- 0 關注
- 770 瀏覽
添加回答
舉報