Hi all,

I'm back with another exception safety musing.  Let me start by stating
that one of the goals of exception safety is to ensure the integrity of
the software in the face of exceptions.  That being the case, consider the
following contrived C++ class.

class MyClass
{
   public:
      MyClass();
      MyClass( const MyClass& other );

      MyClass& operator=( const MyClass& other );

   private:
      Foo* resource1;
      Bar* resource2;
};

Now, let's examine the usual implementation of the assignment operator
assuming some resource creator funcs:

MyClass& MyClass::operator=( const MyClass& other )
{
   resource1 = CreateFooFromCopy( *other.resource1 );
   resource2 = CreateBarFromCopy( *other.resource2 );
   return *this;
}

The problem is that this is not exception safe.  If we throw during the
call to CreateBarFromCopy(), 'this' is in an undefined state.  Generally,
the way to address this is to rewrite the assignment operator in terms of
the copy c'tor:

MyClass& MyClass::operator=( const MyClass& other )
{
   MyClass temp( other );

   std::swap( resource1, temp.resource1 );
   std::swap( resource2, temp.resource2 );
   return *this;
}

The key is in the std::swap.  It is guaranteed, by the standard, never to
throw.  Anything that could throw will happen in the c'tor of the temp
object.  And that's OK, b/c, if that happens, at least this will be
stable.  Only after all possibly throwing things happen, should we mess
with the state of 'this' and we should only mess with the state in a way
that is guaranteed not to throw.

Now, the big question. ;-)

How to achieve this same desired effect in C# WITHOUT having to introduce
try/catch blocks everywhere, IOW, in an EXCEPTION NEUTRAL way.

Thanks,
   -Trey

You can read messages from the Advanced DOTNET archive, unsubscribe from Advanced 
DOTNET, or
subscribe to other DevelopMentor lists at http://discuss.develop.com.

Reply via email to