Thanks Tom for your reply. I will action your suggestions.
ColinG wrote:
Hi,
I have a class named MC.
Header contains the following:
struct tCDV
{
int intC
long lngR;
bool blnE;
CString strC;
};
tCDV* p_cDV;
const int BUFF_SIZE;
std::vector<tCDV*> m_cDV;
Why do you have a vector of pointers to objects. Why not just:
std::vector<tCDV> m_cDV;
tCDV meets the requirements for storage in a vector (it's copyable and
assignable).
Unit contains the following:
MC::MC():
BUFF_SIZE(32)
{
}
MC::Test()
{
p_cDV = new tCDV[BUFF_SIZE];
You create an array of 32 tCDV objects here, but below you only access the
first one. Is this intentional? Are you sure you didn't mean:
p_cDV = new tCDV;
p_cDV->intC = cc; //cc initialised elsewhere in program
p_cDV->lngR = cr; //cr initialised elsewhere in program
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);
}
All the above works fine. My problem is that I receive memory leaks on
program exit and the debugger points to:
p_cDV = new tCDV[BUFF_SIZE];
I attempted to iterate through the vector: m_cDV (via the destructor of
class MC), deleting the pointers p_cDV but to no avail.
You created them with new[], so you need to delete with delete[]:
delete[] m_cDV[i];
So, I scrapped the
iteration code.
Please can someone assist me in resolving this problem.
The best solution is not to use pointers at all (which will often give
faster as well as shorter code). The next best solution is to use either a
pointer container class, or a smart pointer class. That way you don't have
to manually delete the objects at all. See:
http://www.boost.org/libs/ptr_container/doc/ptr_container.html
http://www.boost.org/libs/smart_ptr/shared_ptr.htm
Tom