Search This Blog

Friday, May 13, 2011

ExceptionalC++ Fun: . Exception Safe code (copy constructor & copy assignment)

  • a helper function can be used to copy and allocate memory, try catch, rethrow if something is wrong in that function
a nice style:

template
T* NewCopy( const T* src,
            size_t   srcsize,
            size_t   destsize )
{
  assert( destsize >= srcsize );
  T* dest = new T[destsize];
  try
  {
    copy( src, src+srcsize, dest );
  }
  catch(...)
  {
    delete[] dest; // this can't throw
    throw;         // rethrow original exception
  }
  return dest;
} 
 and use it:

template
Stack::Stack( const Stack& other )
  : v_(NewCopy( other.v_,
                other.vsize_,
                other.vsize_ )),
    vsize_(other.vsize_),
    vused_(other.vused_)
{
} 

No comments: