I've started a project in C++. Memory management in this language is new to me.
I used to create objects with new ()
and then pass around pointers and while it worked, it was a pain to debug and people looked at me funny when they saw the code. I am quite proud of the fact that it didn't leak or segfault (once fixed), but it really was a lot of effort.
list <struct Connection *> users;
struct Connection * accept_connection (const char *name) {
struct Connection * new_node = new Connection ();
new_node->_data = ... // whatever, set it up here
return new_node;
}
struct Connection * new_user = accept_connection (const char *name);
users.append (new_user);
So I have a new strategy for this next version of the project. So far what I am doing is creating objects with new ()
and assigning them a unique integer ID number. I then store the object in a hashed table using the ID as a key. Now items are stored and passed around by the integer ID number and when you do need to de-reference it, you go to the hash table and it returns you either thing *
or NULL
. Hence I no longer experience pointer errors but the speed of the code is somewhat reduced.
typedef unsigned long ID_Number;
// create a user and return the ID
ID_Number create_user () {
ID_Number new_id = assign_unique_id ();
struct User * node = new User ();
node->_id = new_id;
node->_data = ... // whatever, set it up here
add_to_users_dict (new_id, node);
return new_id;
}
list <ID_Number> users;
for_each (users.begin(), users.end(), process_user);
void process_user (ID_Number i) {
struct User * u_ptr = lookup_user_dict (i);
if (u_ptr == NULL) {
// not found in dict
// somehow this guy was deleted
} else {
// we can do stuff with this guy
}
}
Now I am sort of familiar with the basic tenets of programming but being a self-taught hobbyist I am not familiar with the industry practices and tools. What I am basically asking for, is guidelines on memory management:
1) What am I doing right or wrong?
2) Are there any packages or libraries I can use that would help me?
3) What the the standard practices of the industry?
4) Basically what should I be googling or buying for kindle etc?
Today I usually use Python, it does handle a lot of "back end" stuff for me, but I need C or C++ (I guess I'm using plain C plus the stdc++ libs, I am not quite sure where the overlap between the languages is - I just know g++ compiles it fine) for this one particular project for speed/performance reasons: although I suspect some maths genius could provide algorithmic fixes that would speed it no end, though that's a separate question.