Question

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?

Était-ce utile?

La solution

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.

Autres conseils

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 (i.e. the size of the dynamic array and the pointer to the data's location in memory) will likely be stored on the stack.

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.

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top