Jump to content

  • Log In with Google      Sign In   
  • Create Account


C++ Constructors vs. Init() Functions


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
44 replies to this topic

#21 TheComet   Members   -  Reputation: 1448

Like
0Likes
Like

Posted 26 February 2014 - 10:12 AM

 

 


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

 

I feel offloading work into an init() method is somewhat "hackish" and goes against the RAII principle, not to mention everyone who uses your class has to remember to call init().


YOUR_OPINION >/dev/null


Sponsor:

#22 frob   Moderators   -  Reputation: 19628

Like
1Likes
Like

Posted 26 February 2014 - 11:58 AM


I feel offloading work into an init() method is somewhat "hackish" and goes against the RAII principle, not to mention everyone who uses your class has to remember to call init().

If you come from a background of older languages, such as C, pre-90's BASIC, cobol, pascal, ada, or even machine code, RAII means something very different.

 

In the older languages, allocation means you get a blob of memory with completely unspecified data inside. It might be zeros. It might be white noise. It might be the contents from a previous (perfectly valid) object. The next step after allocating is nearly always to initialize the data to known values. It could be bzero() or memset() to initialize the values to zero. It could be to initialize them to otherwise known values. Or sometimes, people would follow the less-than-ideal practice of leaving the memory buffer around with garbage data until they get around to putting real data in.

 

Most modern languages (under two decades old) have strict enforcement of RAII. For example, in Java or C# if you write int i; the compiler automatically applies RAII and initializes it to a value of zero on your behalf. If you write bool b; the language performs RAII and gives you a value of false. 

 

In contrast with older languages (from two decades to nearly seven decades old) in the past when you created an integer it contained whatever happened to be in a register or memory address at the time. It might be zero, 36, 72, or any other value. Unless you initialized it you had no guarantees about the contents until you performed a separate initialization step.

 

 

So really, the RAII cries you hear are mostly an old vs. young interpretation.  Those who have only worked in young languages (Java is still a teenager) and not studied history often interpret RAII as requiring multiple resource allocations and performing costly work. Those who have worked in older languages or who have studied history interpret RAII as just doing something as simple as bzero() after a successful malloc().


Check out my personal indie blog at bryanwagstaff.com.

#23 DarkRonin   Members   -  Reputation: 604

Like
0Likes
Like

Posted 26 February 2014 - 02:47 PM

Wouldn't throwning an exception inside a constructor cause a memory leak, as the destructor would never get called?

This seems hackish to me.

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

Seems funny to throw an exception from the constructor in that case. I'd still go for an init() function.

Edited by lonewolff, 26 February 2014 - 02:50 PM.


#24 Brother Bob   Moderators   -  Reputation: 7868

Like
4Likes
Like

Posted 26 February 2014 - 03:04 PM

Wouldn't throwning an exception inside a constructor cause a memory leak, as the destructor would never get called?

This seems hackish to me.

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

Seems funny to throw an exception from the constructor in that case. I'd still go for an init() function.

The destructor of base classes and already constructed members will be called. If your class doesn't handle resources manually but via smart objects, as it should do, then resources will be correctly released if they were allocated before constructor failed.



#25 cozzie   Members   -  Reputation: 1539

Like
1Likes
Like

Posted 26 February 2014 - 03:08 PM

 

- if you define your own constructor, the 'default' constructor, destructor and assignment operator are no longer applied from the compiler, meaning you need to write them yourself to (look up "the rule of three")

 

Unless somebody made really weird changes to the language, that's simply not true. Creating your own constructor will never prevent default implementations of anything but the default constructor.

 

The "Rule of Three " doesn't say "you must implement all of them, because the compiler doesn't create them", it says "if you need one, you probably need all three". In fact, the big problem IS that the default implementations don't do everything they should in that case.

 

Obvious example:

 


class Demo()

{

    Demo() : ptr(new Thing) {}

    ~Demo() { delete ptr; }

 

    Thing* ptr;

}

 

And you probably don't want to know how often I'm seeing this kind of thing, always hand-waved away with "nah, it's never going to be copied anyway". Unless it suddenly is and "someone" (typically me) gets to spend hours debugging and tracking down the double delete introduced months ago.

 

If the compiler actually would stop creating defaults for assignment and _copy_ constructor (which is the one relevant to the Rule of Three) the code would have the decency to stop compiling. You'd also have an army of C++ coders lynching the person that came up with it.

 

 

Another common rule is that the constructor should only do minimal work to get the object in a valid state. Any heavy lifting that isn't absolutely needed would then go into an init() function.

 

 

Thanks, I've misunderstood it and looked it up:

 

 

The rule of three (also known as the Law of The Big Three or The Big Three) is a rule of thumb in C++ that claims that if a class defines one of the following it should probably explicitly define all three:[1]

These three functions are special member functions. If one of these functions is used without first being declared by the programmer it will be implicitly implemented by the compiler with the default semantics of performing the said operation on all the members of the class. The default semantics are:

  • Destructor - Call the destructors of all the object's class-type members
  • Copy constructor - Construct all the object's members from the corresponding members of the copy constructor's argument, calling the copy constructors of the object's class-type members, and doing a plain assignment of all non-class type (e.g., int or pointer) data members
  • Copy assignment operator - Assign all the object's members from the corresponding members of the assignment operator's argument, calling the copy assignment operators of the object's class-type members, and doing a plain assignment of all non-class type (e.g., int or pointer) data members.

The Rule of Three claims that if one of these had to be defined by the programmer, it means that the compiler-generated version does not fit the needs of the class in one case and it will probably not fit in the other cases either.



#26 frob   Moderators   -  Reputation: 19628

Like
3Likes
Like

Posted 26 February 2014 - 05:24 PM

The rule of three is updated for C++11, to a rule of five.

 

It now also also includes a move constructor and a move assignment operator.


Check out my personal indie blog at bryanwagstaff.com.

#27 SunDog   Members   -  Reputation: 232

Like
0Likes
Like

Posted 26 February 2014 - 05:40 PM

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, 26 February 2014 - 05:43 PM.


#28 Hodgman   Moderators   -  Reputation: 28434

Like
4Likes
Like

Posted 26 February 2014 - 06:24 PM

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.



#29 frob   Moderators   -  Reputation: 19628

Like
0Likes
Like

Posted 26 February 2014 - 06:35 PM

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.


Check out my personal indie blog at bryanwagstaff.com.

#30 Paradigm Shifter   Crossbones+   -  Reputation: 5212

Like
0Likes
Like

Posted 26 February 2014 - 06:37 PM

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, 26 February 2014 - 06:39 PM.

"Most people think, great God will come from the sky, take away everything, and make everybody feel high" - Bob Marley

#31 Hodgman   Moderators   -  Reputation: 28434

Like
4Likes
Like

Posted 26 February 2014 - 06:48 PM

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



#32 Hodgman   Moderators   -  Reputation: 28434

Like
0Likes
Like

Posted 26 February 2014 - 06:53 PM

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.



#33 SunDog   Members   -  Reputation: 232

Like
0Likes
Like

Posted 26 February 2014 - 08:34 PM

 

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, 26 February 2014 - 08:39 PM.


#34 Hodgman   Moderators   -  Reputation: 28434

Like
2Likes
Like

Posted 26 February 2014 - 09:14 PM

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.



#35 Krohm   Crossbones+   -  Reputation: 3015

Like
0Likes
Like

Posted 26 February 2014 - 10:57 PM


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.

#36 Hodgman   Moderators   -  Reputation: 28434

Like
4Likes
Like

Posted 26 February 2014 - 11:25 PM

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.



#37 TheComet   Members   -  Reputation: 1448

Like
2Likes
Like

Posted 27 February 2014 - 03:36 AM


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.


YOUR_OPINION >/dev/null


#38 BitMaster   Crossbones+   -  Reputation: 3770

Like
0Likes
Like

Posted 27 February 2014 - 03:59 AM

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.

#39 Álvaro   Crossbones+   -  Reputation: 12367

Like
0Likes
Like

Posted 27 February 2014 - 07:10 AM

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.

#40 Krohm   Crossbones+   -  Reputation: 3015

Like
0Likes
Like

Posted 27 February 2014 - 08:55 AM

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.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS