BTW, as for assigning 'new' to a raw pointer, I've seen lots of open source libraries do that also. So i thought, why can't I?
Yes, unfortunately it's fairly common, actually. There are numerous good articles on the subject (ie: RAII), but briefly, consider this bit of code:
Code:
struct fatal
{ };
struct object
{
object( bool chaos )
{
if( chaos )
throw fatal( );
cout << "object( )" << endl;
}
virtual ~object( void )
{
cout << "~object( )" << endl;
}
};
void test( void )
{
object*
ptr = new object( false );
object
obj( true );
}
int main( void )
try
{
test( );
}
catch( ... )
{ }
Output:
Here, 'ptr' is not 'protected' by a destructor, so when/if an exception is thrown, it never gets cleaned up. You might be tempted to do something like this:
Code:
void test( void )
{
object*
ptr;
try
{
ptr = new object( true );
object
obj( true );
}
catch( ... )
{
delete ptr; // whoops!
}
}
But that isn't correct either. In this case, the exception was thrown while allocating 'ptr', so an invalid delete is applied!
You might think you could simply call delete if the exception isn't an std::bad_alloc, but unfortunately, that won't work since it could have originated from anywhere between the try block.
The solution, of course, is to follow the RAII strategy:
Code:
void test( void )
{
std::auto_ptr< object >
ptr( new object( false ) );
object
obj( true );
}
Output:
Perfect!