Let me give you an example, you have a simple class. All you want it to do is to Add Strings returned by some method to an ArrayList and read a String at some position afterwards... here's a Dummy:
Using cpp Syntax Highlighting
class Dummy
{
private:
ArrayList * list;
public:
void Construct()
{
int i = 0;
String str;
list = new ArrayList();
list->Construct(20);
for(i=0; i<10;i++)
{
str = SomeOtherMethodReturningAString(i);
list->Add(str);
}
}
String GetStringAt(int i)
{
return *(static_cast<String *>(list->GetAt(i)));
}
};
{
private:
ArrayList * list;
public:
void Construct()
{
int i = 0;
String str;
list = new ArrayList();
list->Construct(20);
for(i=0; i<10;i++)
{
str = SomeOtherMethodReturningAString(i);
list->Add(str);
}
}
String GetStringAt(int i)
{
return *(static_cast<String *>(list->GetAt(i)));
}
};
Parsed in 0.008 seconds, using GeSHi 1.0.8.4
So you think GetStringAt(int i) will work without problem, right??? WRONG!
You see, ArrayList::Add(Object &obj) stores references of objects in the array. Unfortunately, once Construct() is left all what was str is deallocated!! So when you try to read data from those memory spaces afterwards in GetStringAt(), the simulator crashes!
You have to keep those String objects in memory, which means, creating them in heap through pointers/new operator:
Using cpp Syntax Highlighting
class Dummy
{
private:
ArrayList * list;
public:
void Construct()
{
int i = 0;
String * str;
list = new ArrayList();
list->Construct(20);
for(i=0; i<10;i++)
{
str = new String(SomeOtherMethodReturningAString(i));
list->Add(*str);
}
}
String GetStringAt(int i)
{
return *(static_cast<String *>(list->GetAt(i)));
}
};
{
private:
ArrayList * list;
public:
void Construct()
{
int i = 0;
String * str;
list = new ArrayList();
list->Construct(20);
for(i=0; i<10;i++)
{
str = new String(SomeOtherMethodReturningAString(i));
list->Add(*str);
}
}
String GetStringAt(int i)
{
return *(static_cast<String *>(list->GetAt(i)));
}
};
Parsed in 0.008 seconds, using GeSHi 1.0.8.4
See the difference in str? Now you have created a bunch of String objects that exist all by themselves in memory. What if you wanted to delete them? You have no reference anymore! Isn't it a memory leak?
The answer is: No. ArrayList list still has references to it. If you wanted to delete an object you can use
ArrayList::RemoveAt(int index, bool deallocate=false)
See the deallocate parameter? If you set it to true, not will just the reference be removed from the list, but the memory will be wiped clean, too!
You are welcome!

