• Advertisement
Sign in to follow this  

C++ Constructors vs. Init() Functions

This topic is 1423 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement

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

Share this post


Link to post
Share on other sites

Well, constructor's don't have any kind of return value, so, many people use an Init() type function that returns an error code of some sort.

 
The standard way would be to throw an exception from the constructor. (I dont do that either.)
 
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.  Throwing an exception inside a constructor sounds like a bad thing to me.  Is this really the standard way?
Yes, throwing an exception is the standard way of handling a constructor that fails.
http://www.parashift.com/c++-faq-lite/ctors-can-throw.html

Yes, but no, maybe. wink.png
In theory it's the standard mechanism (or using an out-parameter or a zombie object state)... however, I've never actually seen exceptions used in the professional games industry.

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.
I don't want to turn this into a "Are exceptions good/bad" thread, as that's a different topic -- but C++'s exceptions should not be compared to C#/Java/Python/etc's exceptions -- they are a completely different beast. Also C++ is a very complex language, to the point where almost every project leader will define an acceptable sub-set of the language to be used.
 
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.

What about occasions where the error is 'not the end of the world' and the fallback option might not even have anything to do with that class (i.e. you don't need that class if the init() fails).

Can you give an example of where this would happen?

 

In OO, it should be extremely rare to find a valid case for a constructor to fail.

To go off on a rant for a moment --

OO here doesn't mean that you're using an OOP language and you're using keywords like class... It means that you're making use of the large body of software design and engineering knowledge that's been collected under that moniker.

 

To use a straw-man example of what's wrong here, let's say that we've got a Texture class, responsible for managing the lifetime of pixel-data inside the GPU, who's constructor loads an image file from disk. This is a problem because errors can occur during file loading, such as FILE_NOT_FOUND. If that occurs, you'd have to abort from inside the constructor!

Bzzt. You just broke the SRP (Texture is responsible for GPU-resource lifetime management AND disk IO logic), so you're actually using your own methodology here, you're not using OO!

While we're reading up on SRP, we also decide to read about DI and IoC.

Now, we end up with a TextureLoader class, who opens a file, handles FILE_NOT_FOUND errors, and then once it's actually able to load the pixel data from disk, only then is a Texture object constructed and passed that data. Wow, after actually using OO, this whole aborting-construction "problem" went away, look at that...

 

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.

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.

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

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

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.

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

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.

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.

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.

Keep in mind that engines mainly have to do this because some of their customers may want to avoid the use of exceptions at all. If the engine used them, then it would no longer be an appropriate product for those customers.

If you were a customer of those engine companies, there's nothing that would stop you from using exceptions in your own code.

 

As for when the implementations will get better:

* C++ exception implementations on x86-64 are already much more sane than they are on x86... However, most PC games still ship as 32-bit executables... So there's however long that trend takes.

* In console-land, most compilers have either said "Exceptions are off by default; use "/foobar" to enable exception support" or "We stronly recommend you use "/foobar" to disable exception support". This situation has not changed with the new/current next-gen consoles. Maybe next next-gen, in what, another 10 years?

 

The difficulty in obeying the strong exception safety guarantee at all times in C++ will never get easier though.

The job of writing C++ code is made a lot easier if you can just assume that no function will ever throw... I don't know any trends that will impact this particular reason for avoiding them.

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.

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.

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.

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.

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.

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.

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.

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

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement