Sign in to follow this  
Tibetan Sand Fox

Is that way of using constructor really better ?

Recommended Posts

Hello.
Not so long ago I started to learn D3D11 and at the moment I'm swimming through "Beginning DirectX 11 Game Programming" book. I found one thing, which I'm curious about. Author said that constructor’s member initialize list can be more efficient and is better programming practice than letting a constructor do the job in default way.

My question is as in topic, is that way of initializing members really better ?

Example from book:

[CODE]D3DBase::D3DBase() : driverType_( D3D_DRIVER_TYPE_NULL ), featureLevel_( D3D_FEATURE_LEVEL_11_0 ),
d3dDevice_( 0 ), d3dContext_( 0 ), swapChain_( 0 ), backBufferTarget_( 0 )[/CODE]

Thank you in advance for any help. Edited by Agbahlok

Share this post


Link to post
Share on other sites
Cornstalks    7030
[edit: I was waaaay off on my original comment]

@Servant of the Lord: you should prefix literals with an underscore, as literal suffixes not starting with an underscore are reserved for future use. But thanks for reminding me that they exist! Edited by Cornstalks

Share this post


Link to post
Share on other sites
Ryan_001    3475
Most modern compilers will optimize the trivial stuff. So I only stick important things (large items, parent classes, references, ect...) in the initializer list, as I really don't like them. My big issue is that the order items are initlialized in the initializer list is not the same order as they are listed. Which for dependent items can really lead to some hard to track down bugs.

Share this post


Link to post
Share on other sites
mrbastard    1577
[quote name='Ryan_001' timestamp='1349347882' post='4986714']
My big issue is that the order items are initlialized in the initializer list is not the same order as they are listed. Which for dependent items can really lead to some hard to track down bugs.
[/quote]

Ah, but should initialisation be in the initialiser list order, or the order you declared them in the class declaration?

FWIW many coding standards suggest keeping your initialiser lists in the same order as your member declarations for exactly this reason.

Share this post


Link to post
Share on other sites
Ryan_001    3475
[quote name='mrbastard' timestamp='1349349835' post='4986723']
[quote name='Ryan_001' timestamp='1349347882' post='4986714']
My big issue is that the order items are initlialized in the initializer list is not the same order as they are listed. Which for dependent items can really lead to some hard to track down bugs.
[/quote]

Ah, but should initialisation be in the initialiser list order, or the order you declared them in the class declaration?

FWIW many coding standards suggest keeping your initialiser lists in the same order as your member declarations for exactly this reason.
[/quote]

Their order in the class definition is either for readability/clarity, or compactness/cache coherency. No one orders their variables in intialization order, at least, no one outside of C++. Not to mention dependencies can change based on the constructor that is chosen. If the order of initialization occurs in order of the intialization list, then at least you have some control in regards to dependencies. Course IMO the best solution is just to use intializtion lists when absolutely necessary, use standard C++ code the rest of the time.

Share this post


Link to post
Share on other sites
clb    2147
One gotcha though related to initializer lists is that exception safety is not possible if allocating memory to raw pointers.

Consider
[code]
Bar::Bar()
{
throw SomeException();
}

class Foo
{
int *somePointer;
Bar bar;
};

Foo::Foo()
:somePointer(new int[10])
{
}

Foo::~Foo()
{
delete[] somePointer;
}
[/code]

The above code has a memory leak, somePointer is never freed since construction of Bar throws an exception. Edited by clb

Share this post


Link to post
Share on other sites
mrbastard    1577
[quote name='Bregma' timestamp='1349356831' post='4986749']
If there is a compiler that does not issue a warning when you put initializers out of order, you should switch to one that does.
[/quote]

FYI Visual c++ 2012 does not issue a warning about this with /wall (and 'language extensions' disabled fwiw). I know gcc does, and I agree that it's a useful warning.

Share this post


Link to post
Share on other sites
tanzanite7    1410
[quote name='Servant of the Lord' timestamp='1349319567' post='4986638']
[code]
int height = 5ft + 9in;
int weight = 160lbs;
[/code]
[/quote]
O_o, units!? That would be absolutely awesome. Is this some c++11 thing? How does that work? Ref? (Google gave nothing)

Share this post


Link to post
Share on other sites
Cornstalks    7030
[quote name='tanzanite7' timestamp='1349383926' post='4986894']
[quote name='Servant of the Lord' timestamp='1349319567' post='4986638']
[code]
int height = 5ft + 9in;
int weight = 160lbs;
[/code]
[/quote]
O_o, units!? That would be absolutely awesome. Is this some c++11 thing? How does that work? Ref? (Google gave nothing)
[/quote]
They are [url="http://www.codeproject.com/Articles/447922/Application-of-Cplusplus11-User-Defined-Literals-t"]user-defined literals[/url]. Note that they should be prefixed with an underscore to be technically right. You have to declare and define the custom literals yourself.

Share this post


Link to post
Share on other sites
Yep, they are a C++11 feature. Suffixes only, no prefixes at this point. Here's [url="http://en.wikipedia.org/wiki/C%2B%2B11#User-defined_literals"]wikipedia's thoughts[/url].
Alas I can't use it yet, since I'm still on MinGW/GCC 4.6, and those (and most of the above C++11 features I mentioned) are on 4.7. [img]http://public.gamedev.net//public/style_emoticons/default/sad.png[/img]

@Cornstalks: Thanks for the tips about the underscore! The user-defined literals should've also (better/safer coding) returned a user-defined type, like Length, instead of putting it into a generic int: [i]Length myHeight = (4_feet + 8_inches);[/i] Edited by Servant of the Lord

Share this post


Link to post
Share on other sites
Thanks a lot for all those MUCH useful answers ! I didn't even expect to learn so much when I posted this thread. I know everything I wanted to know and even more. Well, I gave most of you +rep. Also you convinced me to use initializer lists more often. It's just drop in the ocean of knowledge I'd like to have, but, well, that's a step. Thank you.

Share this post


Link to post
Share on other sites
Slavik81    360
[quote name='mrbastard' timestamp='1349374702' post='4986828']
[quote name='Bregma' timestamp='1349356831' post='4986749']
If there is a compiler that does not issue a warning when you put initializers out of order, you should switch to one that does.
[/quote]

FYI Visual c++ 2012 does not issue a warning about this with /wall (and 'language extensions' disabled fwiw). I know gcc does, and I agree that it's a useful warning.
[/quote]
Yeah, msvc is the only compiler I know of that doesn't support that warning. For gcc, clang and intel, the flag is -Wreorder.

[url="http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2553854-c-compiler-should-warn-about-wrong-member-initia"]You could vote for it if you want Microsoft to add it.[/url]

Share this post


Link to post
Share on other sites
taz0010    277
[quote]Most modern compilers will optimize the trivial stuff. So I only stick important things (large items, parent classes, references, ect...) in the initializer list, as I really don't like them. My big issue is that the order items are initlialized in the initializer list is not the same order as they are listed. Which for dependent items can really lead to some hard to track down bugs.[/quote]

Why is this being voted down? His gripe about the initialiser list order not being the actual initialisation order is perfectly valid. It's intuitive to assume that the variables are going to be initialised in the order that the initialisation code is written - which is exactly the case whenever you initialise something using the equals sign.

Also mentioned in this topic, ordering your members for alignment or caching reasons can potentially break your code if one member was initialised using the value of another. And since headers are used, the potential error will not even be visible in the file where the initialisation code is actually written.

Personally if I have primitive variables that I need to initialise in a specific order, I'm not going to rely on the class definition order to do it, and that means good old fashioned assignment with the = operator.

Share this post


Link to post
Share on other sites
[quote name='taz0010' timestamp='1349502023' post='4987326']
Personally if I have primitive variables that I need to initialise in a specific order, I'm not going to rely on the class definition order to do it, and that means good old fashioned assignment with the = operator.
[/quote]
And if I need bananas, I'm going to eat good old fashioned apples!

assignment != initialization [img]http://public.gamedev.net//public/style_emoticons/default/wink.png[/img]

By the time your assignment is actually reached, your variables will have already been default-initialized (though it'd [i]probably[/i] be optimized out* if the variable isn't accessed before your assignment).

*[size=2]Which is less a guarantee than the standard-guaranteed initialization order.[/size]

Why wouldn't you rely on the standardized initialization order? The only reason I can think of, is third-party APIs that have weird initialization requirements, requiring you to be 100% sure the API is initialized before you can, for example, load resources. This forces you to break out some initialization outside of the constructor entirely, into separate Init() functions, mucking up RAII for any globally-constructed variables.
But even in that situation, your assignments would still need to happen completely out of the constructor, and it wouldn't be a matter between constructor-body or initializer list, but between the entire construction process or a separate member-function called later.

Share this post


Link to post
Share on other sites
Trienco    2555
[quote name='taz0010' timestamp='1349502023' post='4987326']
Why is this being voted down? His gripe about the initialiser list order not being the actual initialisation order is perfectly valid. It's intuitive to assume that the variables are going to be initialised in the order that the initialisation code is written - which is exactly the case whenever you initialise something using the equals sign.[/quote]

The only time the equals sign has anything to do with initialization is if it is done at the same time as the declaration. So it is [b]still[/b] the declaration order that matters. Or to point it out very clearly
[code]
int x;
x = 10; //This is NOT initialization

int x = 10; //THIS is initialization... also technically a special case syntax for "int x(10);"
[/code]

[quote]
Also mentioned in this topic, ordering your members for alignment or caching reasons can potentially break your code if one member was initialised using the value of another.[/quote]

Which would seem like a very good reason not to do that, instead of saying "I'll simply not do proper initialization, so I can make something work, that shouldn't be done in the first place." How many times do you have a situation, where it's not just as easy to initialize both members by the same parameter/default value? And if one value is calculated from the other, how likely is it that one of those isn't redundant and it is vital for your performance to precalculate them both? Edited by Trienco

Share this post


Link to post
Share on other sites
lauris71    841
[quote name='Servant of the Lord' timestamp='1349504515' post='4987330']
And if I need bananas, I'm going to eat good old fashioned apples!

assignment != initialization [img]http://public.gamedev.net//public/style_emoticons/default/wink.png[/img]

By the time your assignment is actually reached, your variables will have already been default-initialized (though it'd [i]probably[/i] be optimized out* if the variable isn't accessed before your assignment).
[/quote]

And if something smells like banana, tastes like banana and looks like banana, then it probably is banana, even if it is advertised as an apple...
For all primitive types - and that included pointers - assignment is initialization. For all practical purposes. And programming (as opposed to theoretical CS) is practical discipline.

Btw, I find it very disappointing, that people are downvoting Ryan_001 for a shortcoming in C++ standard and suggesting practical solution to overcome it. Many people are using only subsets of C++ standard for various reasons - and calling them bad programmers, summer students or saboteurs because of that is pointless insulting.

Share this post


Link to post
Share on other sites
SiCrane    11839
[quote name='Hodgman' timestamp='1349525505' post='4987371']
I don't know the background behind why the C++ standardization people decided to enforce initialization in declaration order, instead of initialization in initialization order, but IMHO it was a mistake to make that decisiion. Initialization order is bound by logical constraints, but declaration order should only be a concern for memory layout, and should be decoupled from the concern of initialization.
[/quote]
IIRC, it's so that member variables would satisfy the last constructed, first destroyed order that is the general case for variables whose lifetime are managed by the compiler. In theory, the padding/member variable order issue was addressed by allowing the compiler to reorder position of member variables with different access specifiers, but in practice compilers don't actually take advantage of that.

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