Home > C/C++, Programming > Stack and Heap

Stack and Heap

When we define some class like :

class Vector3 {
public:
 float x,y,z;
 Vector3(){ x=0.0f ; y=0.0f; z=0.0f};
}

and then create some code to use it :

1. use stack allocation

Vector3 myVect;
myVect.x = 1.0f;
myVect.y = 2.0f;
myVect.z = 3.0f;

or

2. use heap allocation

Vector3 *myVect = new  Vector3;
myVect->x = 1.0f;
myVect->y = 2.0f;
myVect->z = 3.0f;

which one is better ?

we have to consider several things anyway.

  1. Using stack is faster but very very finite size
  2. Heap is slower because needed to search for available free memory
  3. If using heap,  then have to do clean up manually ( which lead to memory leak problem)
  4. Consider about variable life time
Advertisements
Categories: C/C++, Programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: