PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Better debug features

Hi,

I have already stumbled a few times upon small bugs which could have been prevented by better/smarter debugging features.

The whole library allmost has NO asserts in it! Something any library should be filled to the max with.

My idea is to add better debug support... it is better to have an assert then to have a crash in the release build!

The use of smart pointers I don't like much either. They hide the fact that you left a leak somewhere by 'smartly' removing the class the moment the whole programs exits. I would rather have forgotten to delete something and the compiler telling me so then have it 'magically' removed at the last minute.

The smart pointer phenomenon sounds easy in theorie but it obscures from the responsibility that when you NEW something, you also have to DELETE it.

R
Are you bashing our library? :) YOU'RE FIRED!
;)
Rhino123 · 02 Jul 2002, 14:38 UTC — ehm ehm ehm
of course... what I meant to say is:
If I ever become just as good a programmer as the rest of you then I too can work with libraries without debugging features, since I too won't make any bugs anymore. :wink:

the fact is that now I'm still a lamer and frequently make stupid errors which the library accepts and which make it harder for me to find :?

R
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
Rhino123 · 02 Jul 2002, 16:39 UTC — STL
Hi Japey,

I'll start with saying that I don't have neough experience with Smart pointers to go with you in debate on that one. What I meant to say with the scoped pointer is that I see it now typically used as a member variable of the main game frameworlk class. This means hat if he whole class goe out of scope (the program exits) all the pointers are freed. I think this is 'lazy' programming and it doesn'thelp people to think about when something should be freed. Resources are scarse on the PocketPC and resources should be freed whenever possible. Anyway, about your other agruments about smart pointers: I will have to get back on them...I'll read some stuff about them and then start flaming you if necessary ;^)

About STL:

You example is not very good. STL is definately NOT meant to be used for storing POINTERS!
It breaks down the whole idea of STL. The STL uses containers which store the data in a list for example. If you store pointers in these containers, you have containers having pointers in them pointing to another container.

Thus your int example should have looked like this:

Code:

{
std::vector< int > p;

p.push_back( 0 );
p.push_back( 1 );
p.push_back( 2 );
p.push_back( 3 );

} // out of scope...the whole list gets deleted (its contents inclusive)



This also goes for whole classes!

Code:

class MyClass
{
public:
MyClass();
~MyClass();

};

typedef list<MyClass> MyClassList_t;


{
MyClassList_t MyLocalClassList;
int i;

for(i=0; i<10; i++)
{
MyClass NewClass;

MyLocalClassList.push_back(NewClass); // add 10 classes
}


// now if the program goes out of scope..the whole list gets deleted with all the classes inclusive.. NO LEAKS!
}



If you use STL like this, all the algorithms work better too. For instance, the 'sort' algorithm works because the '<' or the '>' operator of the class is overloaded. This is only possible if the whole class is inserted into the list... not if you use pointers!

Please note that you DO have to make a good copy constructor if your class has pointers in them!

R
"This means hat if he whole class goes out of scope (the program exits) all the pointers are freed."

What you mean is "when the INSTANCE of a class" goes out of scope. Indeed, in the case of the framegame this is the case when the application exits. But for all my code this is exactly what I want, because I really want the GUI resources to be available at all time! I'm not going to reload a gui-button-surface from a file when I'm re-entering the game-menu....

Thus, your argument is not a matter of the scoped_ptr itself, but a matter of the scoped_ptr usage. Thus, an explicit design decision of me.

As for your second point.

"STL is definately NOT meant to be used for storing POINTERS"

This is nonsense. The STL is not meant to do anything in particular. Part of the STL is a collection of containers in which you can put anything you want. You can put instances (Build-in-type, POD's or more complex class structures) in it, but pointers too. It doesn't matter for the STL.

True, the STL is build on value-semantics (for very good reasons) and this seems to imply that the STL is meant to contain objects, and not pointers or references to objects, but this is not true. Any decent reallife situation will come up with a situation where you need pointers to objects in a container.

Start writing your GUI system, and you'll see what I mean.

If, instead, you would have said:

"The STL is not designed to safely contain raw pointers"

you would have been perfectly right! However, this only agrees my point.

Cheers,

Jape

[edited to fix spelling errors]
"Please note that you DO have to make a good copy constructor if your class has pointers in them!"

LOL :), you provide my examples.

What if a class has expensive copy semantics? Consider a class with some complex buffer in it. Obviously the copy-constructor and assigment-operator will be expensive operations because the buffer has to be copied too (or exchanged in rare cases).

Now you want a container of such a class. Performance-wise it would be better to use a container of smart-pointers -that have easy and fast copy constructors and assigment operators- to these objects.

It's precisely these kind of ideas that make the STL seem slow. It's not the STL that is slow, it's the user that makes it slow.

All with a :wink: again ofcourse...

Regards,

Jape
Rhino123 · 03 Jul 2002, 09:44 UTC — Smart pointers, dumb programmers?
I'll start reading about these smart pointers!
they sound like they're the answer to all our troubles ;^)

R