Re: Vector error !!!Help



On Thu, 7 Dec 2006 04:13:02 -0800, MarcoMB
<MarcoMB@xxxxxxxxxxxxxxxxxxxxxxxxx> wrote:

this is sample code:
in my header:

typedef vector <CRectTracker*> TrackerVec;
TrackerVec myVec;

in my OnLButtonDblClk:

CRectTracker* pTracker = new CRectTracker(rect,CRectTracker::solidLine);

CBrush brush1,pOldBrush;
CRect drect;

pDC->SetTextAlign(TA_CENTER);
pDC->SetBkMode(TRANSPARENT);


brush1.CreateSolidBrush(RGB(0, 0, 255));
pDC->SelectObject(&brush1);
SetNormalRect(drect, pTracker->m_rect.left,
pTracker->m_rect.top, 100, 100);
pDC->PatBlt(drect.left, drect.top, drect.Width(), drect.Height(), PATCOPY);


pTracker->m_nStyle &= ~CRectTracker::resizeInside;
pTracker->m_nStyle |= CRectTracker::resizeOutside;
pTracker->Draw(pDC);


myVec.push_back(pTracker);

As several others have noted, there's nothing wrong with what you posted,
so the problem must lie elsewhere. However, unless you're positive that
none of the code between the new and push_back can throw an exception, and
assuming you haven't previously used vector::reserve, your code is not
exception-safe. This is easy to fix, and you've given a perfect example to
apply it to, so for future reference, this is how to do it:

std::auto_ptr<CRectTracker> pTracker(
new CRectTracker(rect,CRectTracker::solidLine));
...
myVec.push_back(pTracker.get());
pTracker.release();

Although auto_ptr::release returns the wrapped pointer, it's too soon for
it to relinquish ownership, because push_back can throw an exception if it
has to grow the vector. Only after the pointer has been added to the vector
is it safe for pTracker to release it.

--
Doug Harrison
Visual C++ MVP
.