954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Creating an object problem

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

class A
{...};

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


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

vector<vector<Student>> a;


Or this:

vector<vector<Student *>> a;

accompanied by

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


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

Emerald214
Newbie Poster
19 posts since Feb 2008
Reputation Points: 10
Solved Threads: 0
 

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.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

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

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

Emerald214
Newbie Poster
19 posts since Feb 2008
Reputation Points: 10
Solved Threads: 0
 

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.

nucleon
Posting Pro in Training
478 posts since Oct 2008
Reputation Points: 163
Solved Threads: 91
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You