[C++]What should I store on the heap?

Started by
9 comments, last by Evil Steve 15 years, 11 months ago
I'm seeing in my C++ that the author sometimes stores string objects on the heap, sometimes integer variables and sometimes not. So, what should I do? Store every variable of a class on the heap?
Advertisement
Only use the heap for very large objects or when you have to (very large = hundreds of kilobytes).

Storing variables and objects on the stack is faster and you don't have to deal with cleaning them up again before you leave a function.
Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.
Quick answer: When any of the following is true:
1. The object is pretty big (More than a few KB)
2. You need to allocate a number of objects that you don't know at compile time
3. You need the object to hang around after the current function returns
Quote:Original post by Evil Steve
Quick answer: When any of the following is true:
2. You need to allocate a number of objects that you don't know at compile time
3. You need the object to hang around after the current function returns


I don't understand 2 and 3.
Example of case #2:
int size;int *array;cin << size; //the value of size is unknown at compile time...//int error[size] //so we can't do this.array = new int[size]; //but we can still allocate an array with appropriate size on the heap


Example of case #3:
-snip-

Case #2 typically occurs very often - basically any time you can't tell in advance exactly how much memory your program is going to use. The third case typically occurs when you want to pass messages or objects between other objects, or when you want to add an object to another object without having it destroyed when the function retutns.
-------------Please rate this post if it was useful.
Quote:Original post by Hnefi
Example of case #2:
*** Source Snippet Removed ***

Example of case #3:
*** Source Snippet Removed ***

Case #2 typically occurs very often - basically any time you can't tell in advance exactly how much memory your program is going to use. The third case typically occurs when you want to pass messages or objects between other objects, or when you want to add an object to another object without having it destroyed when the function retutns.
Case #3 is a memory leak [smile]
You probably want:
void MakeObject(Object **obj){  *obj = new Object();}// Or:Object* MakeObject(){   return new Object();}
Oops. You're right.
-------------Please rate this post if it was useful.
Why was #3 a memory leak?
Because the function copied the pointer, then allocated a new instance to that copy. When the function returned, the copy went out of scope and the created instance was lost.
-------------Please rate this post if it was useful.
Oh.

Thanks for the help :)

This topic is closed to new replies.

Advertisement