简体   繁体   中英

In C++, is created vector or map in a function on stack or heap?

I just have a very simple question but I can not find it through google.

In C++, if we create a integer in a function, I believe it will be in stack. But if we create a vector or a map, for example,

vector<int> a

will it on stack or heap? I believe that's kind of class object(similar to the object created by "new" in java) so probably it should be on heap?

The vector<int> object itself is created in the storage of your choice: if you declare it as a local variable, that would be in the automatic storage.

However, the vector is usually represented as a pair of pointers; the data for that vector is allocated in the dynamic storage area.

Same goes for std::map<K,V> : the object goes wherever you put it (automatic, static, or dynamic memory, based on your declaration) while the data goes into the dynamic storage area.

Starting with C++11 you can use std::array<T> class for fixed-size collections. The data of this collection will go entirely in the storage where you put the collection itself. However, such collections are not resizable.

Yes this will also be created on the stack.

Variables are only created on the heap when new or malloc is called.

The type doesnt really matter, what matters is how its created.

If you're trying to decide whether or not to create a varaible on the stack or dynamically (on the heap), you should consider the lifetime of the object. If you just need it during the scope that its created in, then create it on the stack. Otherwise create it dynamically.

The data for any dynamically sized object like that will be heap allocated. If it were on the stack it would risk an overflow and a program crash if it grew too large.

The object itself (ie the size of the dynamic array and the pointer to the data's location in memory) will likely be stored on the stack.

Here, the vector is stored both on the heap and on the stack. Meaning, the header is on the stack, but as you put elements into the vector, those are dynamically allocated, hence on the heap.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM