Re: How to delete pointers held inside a vector
ColinG wrote:
After reading Tom's reply. I use:
in MC.h:
std::vector<tCDV> m_cDV;
in MC.ccp:
int num = file.read_int();
for (j=0; j < num; j++) {
cc = file.read_ushort(); // file.read_ushort() initialised elsewhere in
program
cr = file.read_ushort(); // file.read_ushort() initialised elsewhere in
program
p_cDV = new tCDV;
p_cDV->intC = cc;
p_cDV->lngR = cr;
p_cDV->blnE = file.read_bool(); // file.read_bool() initialised elsewhere
in program
p_cDV->strC = file.read_string(); // file.read_string() initialised
elsewhere in program
m_cDV.push_back(p_cDV);
}
in destructor for MC class:
for (int x = 0; x < m_cDV.size(); x++) {
delete[] m_cDV[x];
}
which results in the following error:
MC.cpp(59) : error C2440: 'delete' : cannot convert from 'struct MC::tCDV'
to ''
No user-defined-conversion operator available that can perform this
conversion, or the operator cannot be called
MC.cpp(59) : fatal error C1903: unable to recover from previous error(s);
stopping compilation
Colin:
Before you had new and no delete. Now you have delete and no new. If you
put pointers in a container you must new and delete them. If you put
objects in a container you need neither.
--
David Wilkinson
Visual C++ MVP