Sign in to follow this  
MarkS

Try/catch absurdity and calling destructors...

Recommended Posts

MarkS    3502
Let's say I have a class with several pointers that are allocated in the constructor:

[source]
class some_class{
public:
some_class(int);
~some_class();

private:
int *ptr1;
int *ptr2;
int *ptr3;
int *ptr4;
};
[/source]

In the constructor, I would do this:

[source]
some_class::some_class(int some_val)
{
try{
ptr1 = new int(some_val);
}
catch(bad_alloc)
{
std::cout << "Unable to allocate memory." << std::endl;
return; // Skip the rest of the constructor.
}
// Begin the absurdity...
try{
ptr2 = new int(some_val);
}
catch(bad_alloc)
{
delete ptr1; // We can safely assume that ptr1 was allocated by this point.
ptr1 = NULL; // Safe delete...
std::cout << "Unable to allocate memory." << std::endl;
return; // Skip the rest of the constructor.
}
try{
ptr3 = new int(some_val);
}
catch(bad_alloc)
{
delete ptr1; // We can safely assume that ptr1 was allocated by this point.
ptr1 = NULL; // Safe delete...
delete ptr2; // We can safely assume that ptr2 was allocated by this point.
ptr2 = NULL; // Safe delete...
std::cout << "Unable to allocate memory." << std::endl;
return; // Skip the rest of the constructor.
}
try{
ptr4 = new int(some_val);
}
catch(bad_alloc)
{
delete ptr1; // We can safely assume that ptr1 was allocated by this point.
ptr1 = NULL; // Safe delete...
delete ptr2; // We can safely assume that ptr2 was allocated by this point.
ptr2 = NULL; // Safe delete...
delete ptr3; // We can safely assume that ptr3 was allocated by this point.
ptr3 = NULL; // Safe delete...
std::cout << "Unable to allocate memory." << std::endl;
}
}
[/source]

As you can see, depending on the number of pointers to be allocated, this can approach absurd levels rather quickly. However...

[source]
some_class::some_class(int some_val)
{
try{
ptr1 = new int(some_val);
}
catch(bad_alloc)
{
std::cout << "Unable to allocate memory." << std::endl;
return; // Skip the rest of the constructor.
}
// Much more clarity, less absurdity...
try{
ptr2 = new int(some_val);
}
catch(bad_alloc)
{
some_class::~some_class();
std::cout << "Unable to allocate memory." << std::endl;
return; // Skip the rest of the constructor.
}
try{
ptr3 = new int(some_val);
}
catch(bad_alloc)
{
some_class::~some_class();
std::cout << "Unable to allocate memory." << std::endl;
return; // Skip the rest of the constructor.
}
try{
ptr4 = new int(some_val);
}
catch(bad_alloc)
{
some_class::~some_class();
std::cout << "Unable to allocate memory." << std::endl;
}
}

some_class::~some_class()
{
if(ptr1 != NULL)
{
delete ptr1;
ptr1 = NULL;
}
if(ptr2 != NULL)
{
delete ptr2;
ptr2 = NULL;
}
if(ptr3 != NULL)
{
delete ptr3;
ptr3 = NULL;
}
if(ptr4 != NULL)
{
delete ptr4;
ptr4 = NULL;
}
}
[/source]

This is much more clear and compiles, however, I have heard that calling destructors directly is either a bad thing or frowned upon. Am I doing this correctly in the first place? Is there a better way? Is it OK to call the destructor in this case? Edited by MarkS

Share this post


Link to post
Share on other sites
MarkS    3502
[quote name='Bregma' timestamp='1350326419' post='4990470']
Explicitly calling the destructor does not do what you think it does. In particular, calling the destructor of an object from within its constructor will [i]not[/i] affect the members of the class, and you will still leak just as bad as before.
[/quote]

Interesting! OK, time to stop using C-style pointers...

[quote name='Bregma' timestamp='1350326549' post='4990471']
BTW, what is this "safe delete" thing?
[/quote]

It comes from a book, "Teach yourself C++ in 24 hours." I don't remember the exact reason and no longer have the book, but something about calling delete on a NULL pointer is safe, but calling it on an uninitialized pointer can lead to problems. The book mentioned setting the pointer to NULL after delete in the event that delete is called twice (why this would happen, I do not know...). I have always done this. Edited by MarkS

Share this post


Link to post
Share on other sites
Bregma    9202
If you absolute want to avoid using smart pointers, you could try using a cleanup member function.
[code]

class some_class{
public:
some_class(int);
~some_class();

private:
void cleanup();

private:
int *ptr1;
int *ptr2;
int *ptr3;
int *ptr4;
};

some_class:some_class(int some_val)
: ptr1(nullptr), ptr2(nullptr), ptr3(nullptr), ptr4(nullptr)
{
try
{
ptr1 = new int(some_val);
ptr2 = new int(some_val);
ptr3 = new int(some_val);
ptr4 = new int(some_val);
}
catch (...)
{
cleanup();
throw;
}
}

some_class::~some_class()
{
cleanup();
}

void some_class::cleanup()
{
delete ptr4;
delete ptr3;
delete ptr2;
delete ptr1;
}
[/code]
This takes advantage of the fact that it's OK to use the delete operator on a pointer equal to nullptr.

Share this post


Link to post
Share on other sites
[quote name='MarkS' timestamp='1350326568' post='4990472']
OK, time to stop using C-style pointers...[/quote]
More properly: "Time to stop [u][i]defaulting to[/i][/u] using C-style pointers [u][i]to manually manage memory[/i][/u]".
You can still use C-style pointers for non-memory management...
But you shouldn't manually manage memory yourself...
...unless you actually need to for performance reasons (which it sometimes is, even on normal projects).

[quote]It comes from a book, "Teach yourself C++ in 24 hours." I don't remember the exact reason and no longer have the book, but something about calling delete on a NULL pointer is safe, but calling it on an uninitialized pointer can lead to problems. The book mentioned setting the pointer to NULL after delete in the event that delete is called twice (why this would happen, I do not know...). I have always done this.
[/quote]
That's from someone trying to manually manage memory, and instead of fixing the problem (problem: delete gets called twice), pretends the problem doesn't exist by hiding it (delete won't delete a null pointer).

The most direct solution is: don't call delete twice on the same pointer.
A even better solution is: don't call delete (or new) at all*, let smart pointers do it for you.

*[size=2]See previous comment of, 'except when you actually need to'[/size]

[b][edit:][/b] That's not entirely to say setting an invalid pointer to null is bad. Dereferencing a null pointer crashes your program, which is good! So if there is an opportunity to use a pointer after it's been deleted, set it to null... but you shouldn't actually be calling new or delete to manage memory. If I have a raw pointer (that isn't managing memory) that's pointing at something, null is the ideal value to assign to it when it's not valid, because dereferencing null [i]guarantees [/i]to crash, while dereferencing random memory maybe might crash, and maybe might do something incredibly weird that won't show up for several weeks or months.
In some cases it actually even makes sense (usually to avoid unnecessary checks for cleaner code) to delete twice since it has no effect - but it's important to A) know the reason why you raw pointers are set to NULL, and B) not use it to "solve" a program crashing, but actually find out why the program [i]is[/i] crashing.

By default:
- Prefer memory on the stack over dynamic memory.
- Prefer smart pointers over raw pointers when you [i]actually[/i] need dynamic memory.
- Use raw pointers when you [i]actually[/i] need performance in that one area.

Note: [i]'by default'[/i] does not mean [i]'always'[/i]. And in the same way, [i]"prefer smart pointers"[/i] does not mean [i]"never use raw pointers". [/i] Edited by Servant of the Lord

Share this post


Link to post
Share on other sites
LordJulian    151
[quote name='Bregma' timestamp='1350328563' post='4990477']
If you absolute want to avoid using smart pointers, you could try using a cleanup member function.
[code]

class some_class{
public:
some_class(int);
~some_class();

private:
void cleanup();

private:
int *ptr1;
int *ptr2;
int *ptr3;
int *ptr4;
};

some_class:some_class(int some_val)
: ptr1(nullptr), ptr2(nullptr), ptr3(nullptr), ptr4(nullptr)
{
try
{
ptr1 = new int(some_val);
ptr2 = new int(some_val);
ptr3 = new int(some_val);
ptr4 = new int(some_val);
}
catch (...)
{
cleanup();
throw;
}
}

some_class::~some_class()
{
cleanup();
}

void some_class::cleanup()
{
delete ptr4;
delete ptr3;
delete ptr2;
delete ptr1;
}
[/code]
This takes advantage of the fact that it's OK to use the delete operator on a pointer equal to nullptr.
[/quote]
quite good suggestion, BUT: in the cleanup function check for NULL and if not, then delete and assign to NULL. :). I know that delete checks if the pointer is NULL, but for teaching purposes it is good to suggest that. Also, setting it to NULL after deleting is not mandatory, but is, again, good practice and, perhaps, would keep the user to double delete the same pointer and/or access it after deletion.

Share this post


Link to post
Share on other sites
LordJulian    151
Sorry to double post, but, for learning purposes, here's another suggestion: If you want to track "troublesome bugs" with memory allocation (i.e. using pointers after you delete them - happens more often than you think), you set them to an invalid, but easily recognizable value, kinda like 0xfefefefe. Then, when the program blows to bits, you look at the pointer in the debugger, and if it matches (or it is close) the 0xfefefefe, you know you have this problem. enjoy

Share this post


Link to post
Share on other sites
MarkS    3502
[quote name='LordJulian' timestamp='1350329380' post='4990483']
quite good suggestion, BUT: in the cleanup function check for NULL and if not, then delete and assign to NULL. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]. I know that delete checks if the pointer is NULL, but for teaching purposes it is good to suggest that. Also, setting it to NULL after deleting is not mandatory, but is, again, good practice and, perhaps, would keep the user to double delete the same pointer and/or access it after deletion.
[/quote]

After reading what Servant of the Lord wrote on this, I really can no longer say it is good practice. Let's say that I do call delete on a pointer twice. If I set it to NULL, nothing happens and the error is never found and corrected. However, if I don't, the program crashes and the error gets fixed. It would seem to be better practice to not give yourself the ability to do things incorrectly in the first place.

[quote name='LordJulian' timestamp='1350329703' post='4990485']
Sorry to double post, but, for learning purposes, here's another suggestion: If you want to track "troublesome bugs" with memory allocation (i.e. using pointers after you delete them - happens more often than you think), you set them to an invalid, but easily recognizable value, kinda like 0xfefefefe. Then, when the program blows to bits, you look at the pointer in the debugger, and if it matches (or it is close) the 0xfefefefe, you know you have this problem. enjoy
[/quote]

I like this idea. Edited by MarkS

Share this post


Link to post
Share on other sites
[quote]After reading what Servant of the Lord wrote on this, I really can no longer say it is good practice.[/quote]
My point is more against manual memory management and understanding why it should or should not be set to null - I edited my post to clarify. Edited by Servant of the Lord

Share this post


Link to post
Share on other sites
iMalc    2466
Many things you are taught are only true in the context of which you are being taught those things. Outside of that learning context, they may no longer apply, in fact the complete opposite may apply.

"Safe Delete" is one of those things and goes in the same bucket of advice such as:
All your destructors should be marked virtual
Put constants before variables in your if-statement comparisons. (Yoda expressions)
Initialise ALL variables.
Only ever call srand once in your program.
Always use quicksort instead of bubblesort.
Don't ever use macros.
Don't ever use globals.
Don't ever use unsafe functions such as strcpy.
Don't use double-negation (i.e. !!x)
etc...

When you've gained the appropriate level of knowledge and really know what you are doing and why you are doing it, these turn from somewhat good advice into somewhat bad advice. Well bad in that they should not be followed 100% of the time.
"Safe Delete" is probably the worst of these though, in that it should be the first of such advice that you stop following religously. It's there to stop you from being hindered by stupid mistakes caused by a complete lack of knowledge about how pointers work. Once you know all about pointers, you know that it is a waste of time to still follow it.

Share this post


Link to post
Share on other sites
Oberon_Command    6081
[quote name='iMalc' timestamp='1350543904' post='4991357']
Put constants before variables in your if-statement comparisons. (Yoda expressions)
[/quote]

Is this really that widespread? I've only encountered one programmer who did this before, and I'd never heard of it before seeing his code. I find it makes code more difficult to read than is necessary. Certainly I've never bothered with this; confusing = and == is something I do very, very rarely, so I've never seen the need for it. Edited by Oberon_Command

Share this post


Link to post
Share on other sites
I [i]think[/i] it mentions it (and gives pros and cons) in CodeComplete where it's not really arguing for it's use but just presenting it as something that's sometimes done.

I've tried it a little, and then decided to dismiss it from my own coding - I also don't often mistype = for ==, but maybe if I was switching between multiple languages and had a compiler that doesn't issue a good warning for that mistake, it might be worth doing. Edited by Servant of the Lord

Share this post


Link to post
Share on other sites
Madhed    4095
I also find this "yoda comparing" quite confusing (nice term, btw). Also, it won't protect you in the case where you are comparing two variables instead of a variable against a constant.

EDIT: I once worked on a codebase where, apparently for the sake of consistency, smaller than and greater than comparisons were switched as well... [img]http://public.gamedev.net//public/style_emoticons/default/wacko.png[/img] Edited by Madhed

Share this post


Link to post
Share on other sites
jwezorek    2663
[quote name='Oberon_Command' timestamp='1350573945' post='4991447']
[quote name='iMalc' timestamp='1350543904' post='4991357']
Put constants before variables in your if-statement comparisons. (Yoda expressions)
[/quote]

Is this really that widespread? I've only encountered one programmer who did this before, and I'd never heard of it before seeing his code. I find it makes code more difficult to read than is necessary. Certainly I've never bothered with this; confusing = and == is something I do very, very rarely, so I've never seen the need for it.
[/quote]

People do do it. I too find it ugly and not particularly helpful.

The other thing that is like this that people get religious about is only returning from a function at one place at the end of the function. Don't find this particulary helpful either because it often has the effect of making if-statement/conditional nesting deeper which I find harder to read then just bailing out of the function early in relevant cases. Edited by jwezorek

Share this post


Link to post
Share on other sites
Slavik81    360
[quote name='Servant of the Lord' timestamp='1350576009' post='4991459']
I [i]think[/i] it mentions it (and gives pros and cons) in CodeComplete where it's not really arguing for it's use but just presenting it as something that's sometimes done.

I've tried it a little, and then decided to dismiss it from my own coding - I also don't often mistype = for ==, but maybe if I was switching between multiple languages and had a compiler that doesn't issue a good warning for that mistake, it might be worth doing.
[/quote]

Yoda conditionals are a particular annoyance to me. They're less readable, and are not very useful if you write good tests.

More dangerous is accidentally forgetting to break at the end of a case in a switch. It's rare to test for things that you don't do, so a case that falls through and does something extra might not be caught.

Share this post


Link to post
Share on other sites
LordJulian    151

quite good suggestion, BUT: in the cleanup function check for NULL and if not, then delete and assign to NULL. smile.png. I know that delete checks if the pointer is NULL, but for teaching purposes it is good to suggest that. Also, setting it to NULL after deleting is not mandatory, but is, again, good practice and, perhaps, would keep the user to double delete the same pointer and/or access it after deletion.


After reading what Servant of the Lord wrote on this, I really can no longer say it is good practice. Let's say that I do call delete on a pointer twice. If I set it to NULL, nothing happens and the error is never found and corrected. However, if I don't, the program crashes and the error gets fixed. It would seem to be better practice to not give yourself the ability to do things incorrectly in the first place.

 

 

Late reply, but better late... you know the rest.

 

There are two kinds of "best practices".

 

The first one is over-zealous, over-religious, fanatic approach  "the program should blow to bits as soon as I do something stupid, so I get a chance to get all the context I need in order to fix this". This is wonderful, and for a while I was a zealot for this. Again, this is good IN TESTING CONDITIONS, when you have the means to do something about it and another crash won't matter that much.

 

The second one is the motherly, lovely, caring, "peace to the world" type of thinking, in which you try to recover and give the program as many chances to continue like nothing happened as you can. This is good for release code, when a crash is the worst you could do.

Try to have them both and to easily switch between them.

 

Think of this as a theater play/ live show. When doing the repetitions, the director/actors stop at every mistake, correct it and start over; that's why they have the repetitions. But during a live performance, if they stumble, they do whatever they can to carry on until the end of the show and recover the normal flow as soon as possible. Stopping the event and restarting it at each mistake would be too much for the audience. (back to game context) Not to mention that console owners will usually reject your game for any crash :)

Share this post


Link to post
Share on other sites
Khatharr    8812

Yodas are only useful when you're comparing to a retval by putting a long function in the clause:

if(S_OK != BigLongComFunctionNameISawMicrosoftDoThisInSomeOfTheirPublicHeaders(thingy, &otherThingyPtr)) {
  //shimatta
}

After seeing that in the MS header I thought, "Aha!" I used the same method myself like twice and then I was like, "Shouldn't I just catch the retval in a variable and compare the variable so that people can actually read this?"

 

Concerning OP, using smart pointers is really very handy for stuff like that and they are tailored for that kind of usage (with RAII and the strong guarantee in mind). You can have a smart pointer belonging to the class:

 

std::unique_ptr<RscType> m_resourcePtr;

 

Then in the ctor:

 

std::unique_ptr<RscType> resource;
resource.reset(someFuncThatReturnsARscPtrOrNull(arg));
if(resource.get() == NULL) {
  //failure
  return; //or throw - see next para
}

//once all resources are loaded to function-local smart pointers:
m_resourcePtr = resource;
//That syntax will _transfer_ control from the function-owned unique_ptr to the object-owned one.

 

It can make things a lot smoother. You'll like it. smile.png

 

Meanwhile, a constructor can't return a value, so throwing an exception is the only way to communicate internal errors. Why not let your exceptions leave the ctor and catch them at the next point where you can actually handle them?

 

For instance, you had:

 

     try{
          ptr2 = new int(some_val);
     }
     catch(bad_alloc)
     {
          some_class::~some_class();
          std::cout << "Unable to allocate memory." << std::endl;
          return; // Skip the rest of the constructor.
     }

But if you're using smart pointers then you can just allow the bad alloc to break out of the ctor and catch it from the context that's called the ctor. In this way you can communicate other error types by throwing a std::runtime_error("string description") from your ctor. Just catch those in the same place and then you can fetch the description like so:

 

Foo* fooObj;
try {fooObj = new Foo;}
catch(bad_alloc) { //also catches bad_alloc's from inside the ctor
  cout << "I jes cannae do it cap'n. I don't hae the memory!" << endl;
  return -1;
}
catch(runtime_error &err) {
  cout << err.what() << endl;
  return -1;
}
Edited by Khatharr

Share this post


Link to post
Share on other sites
Bruno Sofiato    407

In Java, it's considered a good pratice to use yoda style comparation when comparing to a non primitive constant using the equals() method. It's garanteed that the constant never will be null, so you could get away with a null checking.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this