So I'm trying to get a firm grasp of how I should code collections of objects and pointers, without causing memory leaks... I want to do something like this...
class StackTest
{
public:
StackTest() : m_id(-1),
m_name("")
{ };
StackTest(const int id,
const std::string name) : m_id(id),
m_name(name)
{ };
void SomeFunctionThatCanPreformTasksOnTHISStackTest();
private:
const int m_id;
const std::string m_name;
}
class StackTestCollection
{
public:
void AddStackTest(const StackTest* test);
void SomeFunctionThatCanPreformTasksOnAllStackTests();
private:
std::vector<StackTest*> m_stack_tests;
}
I then have give the collection the function AddStackTest (and make the functions that do things to the collection and the individual StackTest)...
void StackTestCollection::AddStackTest(const StackTest* test)
{
m_stack_tests.push_back(test);
}
Finally my main code base...
// This scopes my_collection so that after the '}' my_collection should get deleted...
{
StackTestCollection my_collection;
my_collection.AddStackTest(new StackTest(0, "First Stack Test"));
my_collection.AddStackTest(new StackTest(0, "Second Stack Test"));
my_collection.AddStackTest(new StackTest(0, "Third Stack Test"));
}
Now I realize that I need to call delete on the pointers to StackTest that are stored in StackTestCollection. I imagine that I would be able to add this to StackTestCollection....
~StackTestCollection()
{
for(auto &test : m_stack_tests)
{
delete test;
}
}
Now this makes me ask a few questions...
1) Would this cause the program to crash during the loop as we are deleting the data in the heap, or would the vector still be stable as the pointer in the stack still exists, but is a dangling pointer...
2) Would I also need to run a delete on the collections m_stack_tests vector? Like this...
delete m_stack_tests;
3) In my main Code I created the collection (StackTestCollection my_collection;), it's my understanding that I only need to control garbage with pointers.... So since my_collection is not a pointer, I don't need to do something along the lines of this.... Correct?
delete my_collection;
I would like to note that this sample program would be running in a large multithread server, where a user logs in and is assigned their own collection. (So each user has their own collection on login, and on log out the data related to the user should be removed too).
Also, I'm not using C++11, so no unique_ptr's :P.