• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
MarkS

Try/catch absurdity and calling destructors...

21 posts in this topic

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
0

Share this post


Link to post
Share on other sites
[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
0

Share this post


Link to post
Share on other sites
[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.
-1

Share this post


Link to post
Share on other sites
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
1

Share this post


Link to post
Share on other sites
[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
1

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
1

Share this post


Link to post
Share on other sites
[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
0

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
0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
[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
1

Share this post


Link to post
Share on other sites
[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.
0

Share this post


Link to post
Share on other sites

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 :)

0

Share this post


Link to post
Share on other sites

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
0

Share this post


Link to post
Share on other sites

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.

1

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  
Followers 0