When creating a new object, i can't decide to use "static allocation" or "dynamic allocation".

class A

int main()
    // A theObject;
   // or A theObject = new A();  ?

In some more complex cases, i don't know what i should do.
Use this:

vector<vector<Student>> a;

Or this:

vector<vector<Student *>> a;

accompanied by

for(i = 0; i < (int)a.size(); ++i)
   a[i] = new Student();

Please explain to me how to use them properly. Thanks thousands.

9 Years
Discussion Span
Last Post by nucleon

use static allocation unless (1) your os and compiler have very limited stack space, or (2) the objects are huge. Declaring STL containers like vector dynamicall is just a waste of time/effort because they only consume about 20 bytes of memory anyway.


Additionally, are there any cases we use this?
vector<int> *a = new vector<int>;

I still don't understand when i should use 'static' or 'dynamic' T_T


It's a matter of where you want to store the object, and whether you wish it to remain in existence after the function in which it was created has returned.

What you are calling "static" allocation (more properly "automatic") saves the data on the stack. Dynamic allocation stores the data in the free store (a.k.a., the heap).

When data is stored on the stack, it disappears when the function that allocated it returns. By storing the data in the free store, you can return it from a function by returning its address, which will still be valid after the function's stack space is freed.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.