About assertions, I agree completely. However, most of this stuff comes from EasyCE which didn't contain assertions. If you feel like going back to this code and adding assertions everywhere, be my guest. I'd rather spend my time on new code. After all, most of the EasyCE stuff is tried and proven...
About smartpointers. You've hit my weak spot here, so if my pro-smartpointer arguments sound a bit harsh then don't be offensed. I really do feel the need to use lots of capitals and exclamation marks here, because too often the use of raw pointers simply results in sloppy code or sub-standard software. Raw pointers are one of the biggest sources of bugs and finalized-application crashes.
"They hide the fact that you left a leak somewhere by 'smartly' removing the class the moment the whole programs exits."
Nonsense! Smartpointers do NOT delete when the application exits! It's the smartpointer policy that decides when the resource is deleted.
Notice the word 'resource' cause smartpointers are not only used for memory but for files, mutex-locks, etcetera too.
Anyway, like I said, it's the policy that decides what happens. In the case of ScopedPtr (which basically is the simplest smartpointer once can provide) the policy is to release the resource once the scope of the smartpointer is left.
Some other policy might be refcounted based (i.e. a shared smartpointer), or yet another policy might imply single-ownerhip through copy- and assigment- transfers (std::auto_ptr).
However, I have NEVER EVER seen a smart pointer that releases its resource when the application exits.
"I would rather have forgotten to delete something and the compiler telling me so then have it 'magically' removed at the last minute."
Once again, a smart pointer does NOT remove something at the last minute. In fact, it removes it as SOON AS POSSIBLE, but NOT ONE MINUTE earlier!!!!
Secondly, how can your compiler tell you that you have forgotten to delete something? True, you can detect this by using a memory-tracker (like Boundschecker, or your own) but not everybody has one remember? Besides, despite theoretical dreaming, in real life programming there ARE differences between release mode and debug mode. You do NOT want to track memory in release mode, yet smartpointers provide you with free (performance-wise) release-mode resource-tracking.
"The smart pointer phenomenon sounds easy in theory"
I agree completely. Many people use smartpointers without knowing what they do, which results in the overly negative and obfuscated image some people have of smartpointers. No offense, but from your remarks I think your (incorrect) ideas about smartpointers are those that lead to these problems too.
"but it obscures from the responsibility that when you NEW something, you also have to DELETE it"
NO NO NO, this is absolutely NOT true.
If there is only a SINGLE idiom you are going to use in your entire programming careeer, let it be "Resource Aquisition is Initialization", commonly reffered to as RAII. This means that the point of creation is responsible for the deletion, and NOT some other place. By using smartpointers you can achieve this goal, because the point of deletion is determined once you create the object (baring refcount fluctuations, which are implicit in a way).
Consider the following code:
- Code:
{
// Create two resources (memory and a file);
char *data = new char[ 40 ];
FILE* f = fopen( "somefile.dat" );
// Read from the file into the char array;
fread( f, data, 1, 40 );
// Do stuff with it;
SomeSomeStuffWithIt( data );
// Release the resources;
delete [] data;
fclose( f );
}
Now consider the same code, but now it needs to cope with exceptions. What can throw exceptions? Basically, anything can. To make the above code exception safe therefore, we have to write the following:
- Code:
{
// Must initialize to zero, to check
// in catch clause.
char *data = NULL;
FILE* f = NULL;
try
{
// Create two resources (memory and a file);
char *data = new char[ 40 ];
FILE* f = fopen( "somefile.dat" );
// Read from the file into the char array;
fread( f, data, 1, 40 );
// Do stuff with it;
SomeSomeStuffWithIt( data );
}
catch( ... )
{
// Release the resources;
delete [] data;
if ( f ) fclose( f );
throw;
}
// Release the resources;
delete [] data;
fclose( f );
}
Note the need to release the code twice, but with the added variation of the if ( f ) clause. This duplication of code IS NECCESARY to cope with exceptions.
However, you might argue, we're not using exceptions in our code. This is not true cause new can throw an exception in all cases. Then you might argue, if new throws an exception something so serious happened that I don't care anymore. Let the application crash cause it doesn't matter.
I agree, this is acceptable. However, the story doesn't end here. Let's forget about exception handling for a moment, and consider other failures and multiple return paths....
- Code:
{
// Create two resources (memory and a file);
char *data = new char[ 40 ];
if ( data == NULL ) return;
FILE* f = fopen( "somefile.dat" );
if ( f == NULL )
{
// something went wrong;
return 0; // THIS IS A MEMORY LEAK;
// Read from the file into the char array;
if ( fread( f, data, 1, 40 ) < 0 )
{
// Something went wrong;
return 0; // THIS IS A RESOURCE LEAK;
}
// Do stuff with it, and return that data;
int i SomeSomeStuffWithIt( data );
// Release the resources;
delete [] data;
fclose( f );
// Done;
return i; // Note the need to
// explicitly store the return value;
}
See where the memory leak is? The correct version would look like this:
- Code:
{
// Create two resources (memory and a file);
char *data = new char[ 40 ];
if ( data == NULL ) return;
FILE* f = fopen( "somefile.dat" );
if ( f == NULL )
{
delete []data;
return 0; // OK, memory released;
}
// Read from the file into the char array;
if( fread( f, data, 1, 40 ) < 0 )
{
delete [] data;
fclose( f );
return 0; // OK, file and memory released;
}
// Do stuff with it, and return that data;
int i SomeSomeStuffWithIt( data );
// Release the resources;
delete [] data;
fclose( f );
// Done;
return i; // Note the need to
// explicitly store the return value;
}
See the code-duplication? For each function-exit point you need the resource-release. With more function-exit points (which are not uncommon, especially when dealing with resources at which all sorts of things can go wrong) things get worse.
Also note the need to store the return value of the DoSomeStuffWithIt function. We can't just do
return DoSomeStuffWithIt();
because we still need to release the resources afterwards.
Now I present you the EXCEPTION-SAFE smart-pointer version of the same routine:
- Code:
{
// Create two resources (memory and a file);
ScopedArray< char > data( new char[ 40 ] );
if ( data.Get() == NULL ) return 0;
ScopedFile f( fopen( "somefile.dat" ) );
if ( f.Get() == NULL ) return 0;
// Read from the file into the char array;
if( fread( f.Get(), data, 1, 40 ) < 0 )
{
return 0;
}
// Do stuff with it, and return that data;
return SomeSomeStuffWithIt( data );
}
See? Less lines, easier to maintain, no code duplication, and exception safety without the added cost! And also the resources are released WHEN THE FUNCTION EXITS, not when the application exits.
Continueing this smartpointer manifest, let's talk about STL. I'll keep it short, but STL and raw-pointers provide material for hours of examples where things go wrong.
Consider the following code:
- Code:
{
std::vector< int* > p;
p.push_back( new int( 0 ) );
p.push_back( new int( 1 ) );
p.push_back( new int( 2 ) );
p.push_back( new int( 3 ) );
// Leave scope, and p is deleted. But the
// integers ARE NOT! This is a MEMORY LEAK;
}
To resolve this, you have to write:
- Code:
{
std::vector< int* > p;
p.push_back( new int( 0 ) );
p.push_back( new int( 1 ) );
p.push_back( new int( 2 ) );
p.push_back( new int( 3 ) );
for ( std::vector::iterator iter = p.begin();
iter != p.end(); ++iter )
{
delete *iter;
}
// Or alternatively write a functor
// and use for_each.
}
See? Not easy to maintain and a horror once you get multiple return points from a scope or introduce exceptions.
It get's worse. A common idiom to remove items from a container is the erase-remove idiom. For example to remove all elements pointing to a certain object, one might use
- Code:
erase( remove_if( p.begin(), p.end(), SomeFunctor() ), p.end() );
// Where SomeFunctor is a predicate
// returning true if the parameter points to
// the desired object
However, this has TWO dangerous errors! The most obvious one is that the pointers themselves are removed, but the memory pointed to not! Thus you have a memory leak. Howevever, the more DANGEROUS yet, less obvious mistake is that you've actually LOST references to memory by using the remove-idiom on raw pointers. So even if you would remember to delete them, you can't cause you've lost the references....
It goes too far here to explain the remove-algorithm to argue my point. It's all in the book Effective-STL which I will bring for you this friday.
However, I it is a safe conclusion that STL and raw-pointers are NOT compatible.
______________________________________________
I've only given a few short examples, and you may not yet be converted. Hell, it took me a year in between seeing the first smartpointer (thank you Lambert, grbml) and finally seeing the light.
If this story doesn't convert you, I'd be more than happy to bring another book (Modern C++ Design) which has a great pro-smartpointer rationale. I'm not trying to sound zealot here, I just think that software-engineers in general (worldwide) should be able to write better code...
Ah well, I'm just Jaap ofcourse. What do I know. Visit alt.comp.lang.c++.moderated and ask about smartpointers there. The newsgroup is full of C++ gurus much much much smarter than any of us (I'm talking Meyers, Sutter, Alexandruescu, Soustrup here) and they all agree about smartpointers....
And as a last remark, this post was not meant to be offensive in anyway. By taking a stand against smartpointers you show that at least you thought about their uses, which is a hell of a lot better than people just blindly accepting smartpointers and then using them in the wrong way (and thus producing the negative image).
So take all of this with a ;)
Cheers,
Jape