亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

分配向量后,它們是否使用堆或堆棧上的內存?

分配向量后,它們是否使用堆或堆棧上的內存?

C++
滄海一幻覺 2019-11-05 10:36:42
以下所有陳述均正確嗎?vector<Type> vect; //allocates vect on stack and each of the Type (using std::allocator) also will be on the stackvector<Type> *vect = new vector<Type>; //allocates vect on heap and each of the Type will be allocated on stackvector<Type*> vect; //vect will be on stack and Type* will be on heap. 如何Type在一個vector或任何其他STL容器中為內部分配內存?
查看完整描述

3 回答

?
當年話下

TA貢獻1890條經驗 獲得超9個贊

vector<Type> vect;

將vector在堆棧上分配,即標頭信息,但在免費存儲(“堆”)上分配元素。


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

在免費商店中分配所有東西。


vector<Type*> vect;

將vector在堆棧上分配,并在免費存儲區上分配一堆指針,但是這些指針的位置由使用方式決定(例如,您可以將元素0指向免費存儲區,將元素1指向堆棧)。


查看完整回答
反對 回復 2019-11-05
?
慕斯王

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);

  }


查看完整回答
反對 回復 2019-11-05
?
皈依舞

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指針)。


順便說一句,該實現實際上可以將某些矢量(通常為小尺寸)完全存儲在堆棧中。我不是知道任何這樣的實現,但是可以。


查看完整回答
反對 回復 2019-11-05
  • 3 回答
  • 0 關注
  • 770 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號