Original Post
I've been having problems with a program and eventually found the source of the problem which is demonstrated by the following code: Running this will cause the program to crash because the deconstructor is called twice, once when the cString object is destroyed and again when the list is destroyed. Although I can see the cause of the problem I've been having a hard time trying to find a solution to it. The following code is from my actual project: As you can see, the code creates a temporary object, sets the properties (including memory allocation in SetName), and then appends this to the m_FileTable list. However, when the function end is reached, the temporary object is destroyed, which destroys the string which the object in the list is still pointing to. What is the best way to avoid this problem?
#include <list>
#include <iostream>
class cString
{
public:
cString (){ str = 0; }
virtual ~cString () { if (str != 0) delete [] str; }
char* str;
};
int main ()
{
std::list <cString> List;
cString string;
string.str = new char [32];
List.push_back (string);
return 0;
}
{
// ...
cARC_FileInfo newFile;
newFile.SetName (strName);
newFile.SetFilePath (strFilePath);
newFile.SetLength (0);
newFile.SetOffset (0);
m_FileTable.push_back (newFile);
return true;
}