C++ pointer to struct [edited]

Started by
10 comments, last by MarkusPfundstein 12 years, 7 months ago
Though I am for using vectors, you still need to learn about memory allocations and deallocations. C++ has so many pitfalls that you need to be aware of. Improper usage of memory can turn your app inside out and you won't know why, and it's hell of a bitch to track down.
Advertisement
the vector class is pretty cool if u have to change the size of memory at runtime.. consider the following example


t_tile **tile;

void makeMap (int rows, int cols) {

*tile = (t_tile**)malloc(sizeof(t_tile*rows));
for (int i = 0; i < rows; i++) {
tile = (t_tile*)malloc(sizeof(t_tile*cols));
}

}


So, now we have enough memory for a 2d array which we can access easily through tile[j]..
What if we want to change the map size on runtime AND we don't want to delete our old memory because we still need? (Consider a map editor)
We would have to do the following



void resizeMap (int rows, int cols) {

// allocate temp 2d array of the same size as the old map
t_tile **temp;

*temp = (t_tile**)malloc(sizeof(t_tile)*cols);
for (int i = 0; i < old_rows; i++) {
temp = (t_tile*)malloc(sizeof(t_tile)*rows);
}

// copy the old value into temp
for (int i = 0; i < old_rows; i++) {
for (int j = 0; j < old_cols; j++) {
temp[j].dataset = tile[j].dataset;
}
}

// recalculate memory for tiles
*tile = (t_tile**)realloc(NULL, sizeof(t_tile)*rows);
for (int i = 0; i < rows; i++) {
tile = (t_tile*)realloc(NULL, sizeof(t_tile)*cols);
}

// copy temp into new reallocated memory
for (int i = 0; i < old_rows; i++) {
for (int j = 0; j < old_cols; j++) {
if (
tile[j].dataset = temp[j].dataset;
}
}

for (int i = 0; i < old_rows; i++) {
free(*temp);
}

free(temp);

old_rows = rows;
old_cols = cols;

}



pretty much messy code.. btw, if there are any mistakes.. don't blame me.. its 1:10 AM here, i wrote that out of my memory after watching three apple dev videos about __weak and __autoreleased objects ^^

under the bottom-line, we see that this is a lot of code.. the vector class takes ALL this away from us!!! we can add and remove objects as we want and it is pretty efficient as well..

Only thing why i don't use it pretty often is...

it leaks when u store a pointer to a class in the vector.. so don't use

class_name *object with a STL vector.. only use class_name object

also keep in mind that it will always call the constructor and the destrunctor if u add or remove objects.. this can especially be very tricky if u store openGL textures in one memory locations accessed by a lot of objects and u delete this memory by calling glDeleteTexture in a destructor.. if one object gets removed from the vector list, all objects loose their reference..

i go to sleep now, good night :-)

I open sourced my C++/iOS OpenGL 2D RPG engine :-)



See my blog: (Tutorials and GameDev)


[size=2]http://howtomakeitin....wordpress.com/

This topic is closed to new replies.

Advertisement