I allocate objects on the heap and under some circumstances I combine them into a new object (my Foo class mainly contains 2-3 STL containers). (An alternative would be to use copies, but I guess that would be less efficient.)
These operations may fail, thus exceptions may be thrown. Unless I release the dynamic memory whenever I throw an exception, I will have memory leaks.
Would auto_ptr/unique_ptr make sense in this case? I guess so since Combine is a "sink", but what if I wanted to use f1 and f2 after the call to Combine?
Thanks!
Here's my code:
Foo* MakeFoo( )
{
Foo* foo = 0;
Foo* f1 = SimpleFoo( );
if( f1 )
{
Foo* f2 = SimpleFoo( );
if( f2 )
{
Foo* combined = Combine( f1, f2 );
delete f2;
delete f1;
}
else
foo = f1;
}
delete foo;
}
Foo* SimpleFoo( )
{
Foo* f = 0;
if( something )
{
f = new Foo;
if( somethingElse )
throw std::runtime_error( "Error" ); // Memory leak
}
return f;
}
Foo* Combine( const Foo* f1, const Foo* f2 )
{
assert( f1 );
assert( f2 );
// Memory leak in MakeFoo( )
if( something )
throw std::runtime_error( "Error" );
Foo* foo = new Foo;
// Maybe one could also simply modify f1
foo->Add( *f1 );
foo->Add( *f2 );
return foo;
}