I have a class that holds a few vectors, I’m not sure which method is the best but when the I call the destructor they should be deleted from memory.
HEADER:
class Test
{
public:
Test();
~Test();
void AddString(char* text);
void AddString(string text);
private:
char * StringToCharPointer(string value);
vector<char*> *pVector;
}
CPP File:
Test::Test()
{
};
Test::~Test()
{
vector<char*>::iterator i;
for ( i = pVector->begin() ; i < pVector->end(); i++ )
{
delete * i;
}
delete pVector;
};
char * Test::StringToCharPointer(string value)
{
char *pChar = new char[value.length()];
strcpy(pChar, value.c_str());
return pChar;
};
Test::AddString(char* text)
{
pVector->push_back(text);
};
Test::AddString(string text)
{
pVector->push_back(StringToCharPointer(text));
};
so here’s pretty much all the methods that I use, but what’s wrong?
Firstly,
iis an iterator on the vector, it is not the pointer stored in the vector.*iis the pointer stored in the vector, so if you’re going to delete anything it should be that.Secondly,
delete *iis only valid if the object pointed to by*iwas allocated withnew. Notnew[], not malloc, and it doesn’t point to a string literal. Since you don’t say how your data was allocated, it is not possible for us to say whether or not you are freeing it correctly.It seems likely that you should use a
std::vector<std::string>.Update for updated question:
HEADER:
CPP file: