• 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
blueskies9041

C++ Constructors vs. Init() Functions

44 posts in this topic

Trivial constructors (basically constructors that might initialize variables to a defined state, but don't do anything like dynamically allocate memory), along with trivial copy constructors and destructors make RAIII much easier, without having to resort to shared/smart/auto pointers.   The problem with C++ is that constructors and destructors are often called implciitly without the programmer realizing it, in addition the compiler generates default constructors in any case.   Using a complicated constructor leads one to use pointers to objects and call new(), when really standard simple scoped objects would be a much better solution.

 

Example:

class A {
private:
       int* intPtr;
       int intPtrSize;
public: 
       A()  {  intPtr = nullptr; inttPtrSize = 0; }
       A(const &A other) { intPtr = nullptr; }       // no copy constructor
       virtual ~A  { }                                          // empty destructor
       void init(int size)   { intPtr = new int[size]; inttPtrSize = size; }
       void dispose()  { delete[] intPtr; intPtr = nullptr;}  
};
 
class B {
private:
      A a;
      float *floatPtr;
      int floatPtrSize;
public:
      B() {  floatPtr = nullptr; floatPtrSize = 0; }   
      B(const &B other) { floatPtr = nullptr; }   
      virtual ~B() { } // empty destructor
      void init(int aSize, int bSize)  { a.init(aSize);  floatPtr = new float[bSize]; floatPtrSize = bSize; }
      void dispose()  { a.dispose(); delete[] floatPtr; floatPtr = nullptr; }  
}

In the above example, I am using RAII with respect to A's lifetime in B.   Theres no complicated constructor chaining, and no possibility of an exception being thrown during A's constructor, which would leave B's floatPtr in an undefined state.    On the destructor side,  I don't do anything and have to call an explicit dispose() method.  This makes the code much clearer as to whats actually going on, rather than implicit destrucotrs being called   At least, if I try to do something with "unitilaized B", the program will crash trying to dereference a null pointer. This is a much easier bug to track down, than a memory leak. 

 

Bottom line for me, is that the only two sane choices are to use something lie the above pattern, or wrap everything around smart pointers to avoid shooting yourself in the foot.

Edited by SunDog
0

Share this post


Link to post
Share on other sites

So, I would treat "I need to throw an exception from this constructor" as a code-smell, indicating that you probably need some DI and IoC up in yo code.

 

Which brings us right back to items covered on page one of the discussion...

 

 

RAII means to initialize things to be ready to use. "Empty" and "Disconnected" are perfectly valid definitions of ready to use, and for non-trivial objects are usually the best default.

 

 

I would never do anything "complicated" inside the constructor, like loading images, setting up textures, etc.  I would just initialise member variables to a known state and leave the other stuff for an init function/method or using getters/setters, depending on the situation.  I wouldn't do anything that could throw exceptions inside a constructor.

 

 

The best constructors are the ones that instantly init to an empty or blank object, deferring the heavy processing work so the developer can schedule the work to a time and place that is appropriate.

 

If you must do work, and especially if that work can fail, it seems like you are doing more than constructing an object.

0

Share this post


Link to post
Share on other sites

Init is a terrible name though, since it doesn't really describe anything.

 

Bind, Open, Connect, etc. much better.

 

EDIT: Init is ok for "call this first, don't do anything else beforehand" but that's probably better in a constructor unless reasons already posted here (lots of work, fails a lot, etc.) apply.

Edited by Paradigm Shifter
0

Share this post


Link to post
Share on other sites

So, I would treat "I need to throw an exception from this constructor" as a code-smell, indicating that you probably need some DI and IoC up in yo code.

Which brings us right back to items covered on page one of the discussion...

I would never do anything "complicated" inside the constructor, like loading images, setting up textures, etc.  I would just initialise member variables to a known state and leave the other stuff for an init function/method or using getters/setters, depending on the situation.  I wouldn't do anything that could throw exceptions inside a constructor.

The best constructors are the ones that instantly init to an empty or blank object, deferring the heavy processing work so the developer can schedule the work to a time and place that is appropriate.
 
If you must do work, and especially if that work can fail, it seems like you are doing more than constructing an object.

If an empty state makes sense, like for a std::vector, then sure.
Otherwise, an empty state followed by initialization is still a code smell, indicating you need some DI and IoC in there.

Aregee's quote there particularly indicates that DI is the solution, rather than two-phase initialization.

0

Share this post


Link to post
Share on other sites

 

The problem with C++ is that constructors and destructors are often called implciitly without the programmer realizing it, in addition the compiler generates default constructors in any case.

This translates to: 
The people working on this project only know C, and are only just learning C++ now...
 
If you're part of an organization with a lot of C programmers, and you're transitioning to C++, then this might be a very valid decision...
But if you're trying to hire new programmers to work on a C++ project, people who don't realize how constructors/destructors actually work will fail the technical interview and not be hired...
 
Your example code is a lot smaller and clearer when written using C++ constructs:

class A : boost::noncopyable {
	int* intPtr;
	int intPtrSize;
public: 
	 A(int size) : intPtr(new int[size]), intPtrSize(size) {}
	~A()  { delete[] intPtr; }
};

class B : boost::noncopyable {
	A a;
	float *floatPtr;
	int floatPtrSize;
public:
	 B(int aSize, int bSize) : a(aSize), floatPtr(new float[bSize]), floatPtrSize(bSize) {}
	~B() { delete [] floatPtr; }
};

It's also safer in that it cannot be misused by the programmer. E.g. A requires a size value for it to be initialized. If inside B, we remove "a(aSize),", then you'll get a compile error saying that you've forgotten to initialize a.
In your original code, if we remove "a.init(aSize);" from B's init function, we get no such compile-time error.
Your original code also allows the user's of A/B to call init or despose more than once per object, or not at all. The C++ method ensures they're called exactly once each, and in the right order.
 
You've also broken the rule of three by having custom clean-up code in a class without custom cloning/assignment code. This lets the users of A/B create code buggy code, like this:

A one; one.init(42);
A two; two = one;
one.despose();
two.despose();//double delete bug

If you actually use C++, then such bugs aren't possible, with compile-time errors generated instead:

{ A one(42)
  A two; //compile error - default initialization disabled
  A two(one); // compile error - copying disabled
  A two(0);
  two = one;//compile error - assignment disabled
}//destructors called, double delete bug impossible

I'll stick with cleaner, simpler, safer, more predictable code tongue.png

 

 

What happens with that approach if you make an array of A objects ?   What happens if an exception gets thrown in A's constructor?  (B is left in an undefined state)

 

Also, boost isn't an integrable part of C++.  Alot of people dislike it because it slows down compilation time considerably.  I also don't like the idea of relying an external library for something so basic like proper initialization of my objects.

Edited by SunDog
0

Share this post


Link to post
Share on other sites

1) What happens with that approach if you make an array of A objects ?
2) What happens if an exception gets thrown in A's constructor?  (B is left in an undefined state)
3) Also, boost isn't an integrable part of C++.

1) You use a std::vector / etc instead of C arrays, if required.
2) IMHO, I'm personally of the opinion that C++ exceptions are broken by design and shouldn't be used....
That said, an exception thrown by A's constructor would bubble up out of B's constructor too though, so you won't have a B object afterwards.
In this particular example, the floatPtr var won't be initialized yet, so you won't have a leak. In other cases yes you could get leaks, so a unique_ptr/auto_ptr/etc should be used instead of a raw float*... or you should fix your OO design as in the other post above, using DI to move the failable parts to before the constructor.
 
This is the same headache with or without constructors though -- it just comes down to whether you want to keep the "strong exception safety guarantee" rule in mind when you write every line of code. Besides C++ exceptions being (IMHO) broken, this is another reason why I'd personally choose to avoid using them... Especially if you can't trust your staff to know construction/destruction rules, I wouldn't trust them to know the strong exception safety guarantee rule either!

try
{
  B b; b.init();
  b.dispose();
} catch( A::Exception& e )
{
  //did b leak?
}

3) I used the boost version so I wouldn't have to explain the non-copyable idiom.
Every (non-boost using) C++ code-base should have it's own version of this idiom, something like:

//noncopyable.h
#pragma once
class NonCopyable
{
public:
	NonCopyable(){}
private:
	NonCopyable( const NonCopyable& );
	NonCopyable& operator=( const NonCopyable& );
};

Or alternatively, the idiom should show up repeatedly in the code-base, where objects with custom destruction logic, but no cloning logic have private copy/assignment operators as above, in order to fulfill the rule of three.

2

Share this post


Link to post
Share on other sites


Over the past 10 years I've used about 7 different professional C++ game engines (on about a dozen different products), and they all avoided the use of C++ exceptions completely.
How long do you think this will continue being the case? I find exceptions extremely productive in general, I hope this goes away with this-gen.
0

Share this post


Link to post
Share on other sites

For large/complex professional game engines, this commonly includes:

don't use the standard new/delete/malloc/free (use some engine-specific replacement / wrapper),
don't use std containers (as they will call new, and custom allocator mechanisms are broken),
don't use exceptions (as writing to satisfy the "strict exception safety" guarantee is hard in C++, there's a performance impact, and some gaming platforms may not even support them),
don't use RTTI or dynamic_cast,

and sometimes includes (these used to be common 10 years ago, but not so much today).

don't use anything in std,
don't use templates.

But that's just C without the ++, what's the point of having all of these fancy features if you can't use them? I'd also think that writing your own containers is more error prone. Then again, I was never affiliated with the gaming industry, I'm sure these decisions are for the best.

2

Share this post


Link to post
Share on other sites
My guess would be a lot of that is being burned by bad compilers on consoles in the past and probably still suffering from some problems there. Also, a frighteningly high number of "C++ programmers" (even supposedly professional) always seem to me to be stuck at "C with classes" and unable/unwilling to move beyond that.

As a counterexample we had a rather largish piece of desktop software (non-game but heavy in the 3D graphics department) and the core of it got moved to smartphones. There are a lot of problems going that way, especially if the code base is old and does not always contain best practices and suffered from quiet a few lax coding guidelines in the past.
Among the chief problems were neither exceptions, std::containers nor the lack of manual memory management though.

I'd say that is at least a partly relevant experience because for the usual hobbyist programmer consoles are completely not an option, while smartphones are. And even if you go professional enough for consoles to be an issue you already have to deal with a multitude of hardware-specific issues so that these points are above are just one among many.
0

Share this post


Link to post
Share on other sites

What happens if an exception gets thrown in A's constructor?  (B is left in an undefined state)


Actually, the problem is the other way around. If A has been successfully constructed but the allocation of floatPtr throws an exception (and I am not sure how saying "I don't use exceptions" can help you here), the destructor of B will not be invoked and A will leak. OK, if you ran out of memory, you may have worse things to worry about than A not being deleted, but it's still somewhat wrong.

I am not going to claim that all the code I write has strong exception-safety guarantees, but this common problem is fixed by always wrapping each dynamically-allocated member in a class that guarantees exception safety (a smart pointer would do, or something like class A in Hodgman's example). You simply don't write classes that hold two raw pointers to dynamically allocated data, and you don't write mixed classes like class B above.
0

Share this post


Link to post
Share on other sites

Uhm, that's bad news for me. I've spent quite some effort in making my design more modern, mostly because...


The job of writing C++ code is made a lot easier if you can just assume that no function will ever throw...
... but there is the benefit of being able to assume no function can fail.
0

Share this post


Link to post
Share on other sites

Uhm, that's bad news for me. I've spent quite some effort in making my design more modern, mostly because...

The job of writing C++ code is made a lot easier if you can just assume that no function will ever throw...

... but there is the benefit of being able to assume no function can fail.
Throwing an exception is a method to indicate a failure.
Returning an error code is a method to indicate a failure.

While both indicate failure, the methods, costs, benefits, risks, and rewards of the two are radically different. The pros and cons of each have been discussed many times in different topics already.

For this discussion it is enough that the console game industry has rejected c++ exceptions as a method of indicating failure. Collectively they have decided that within the niche industry the costs of c++ exceptions outweigh the benefits.

If you want to start a new topic on it (AFTER searching the forum to read the previous flame wars, debates, and discussions) it would probably be better than redirecting this discussion on constructors versus utility initialization functions.
2

Share this post


Link to post
Share on other sites

But that's just C without the ++, what's the point of having all of these fancy features if you can't use them? I'd also think that writing your own containers is more error prone. Then again, I was never affiliated with the gaming industry, I'm sure these decisions are for the best.



10 years ago is a long time. C++ compilers weren't so great back in the day, especially on console's so those older games were probably essentially C with Classes. More modern C++ without std containers or exceptions with custom allocators is very powerful though and won't look very much like C code with inheritence, polymorphism, and templates.
0

Share this post


Link to post
Share on other sites

...if the allocation of floatPtr throws an exception (and I am not sure how saying "I don't use exceptions" can help you here), the destructor of B will not be invoked and A will leak.

You can avoid that by using "no throw new" instead of "regular new" (or by using the compiler command like options to disable exception support). This is one reason why large projects often ban 'new' and force you to use a macro like MY_NEW (e.g. Then they can make all allocations provide the no-throw guarantee).

On the topic of games, if you run out of RAM, you pretty mic just want to crash with a good debugging dump, and then fix your code :)

Also, if you choose not to use exceptions, you'll have no catch statements at all, so any use of throw at all will end up bubbling to main and aborting your app ;-)

I am not going to claim that all the code I write has strong exception-safety guarantees, but this common problem is fixed by always wrapping each dynamically-allocated member in a class that guarantees exception safety (a smart pointer would do, or something like class A in Hodgman's example). You simply don't write classes that hold two raw pointers to dynamically allocated data, and you don't write mixed classes like class B above.

thats the "weak exception safety" guarantee, which should be mandatory if you're choosing to use exceptions in your project.
0

Share this post


Link to post
Share on other sites

 

But that's just C without the ++, what's the point of having all of these fancy features if you can't use them?

You misunderstand.

I didn't say that! :)

0

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