Jump to content
  • Advertisement
Sign in to follow this  
vlj

Is there a way to change initialisation order while keeping object layout ?

This topic is 938 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

In C++ the order of the member in a class is the order in which they are initialized.
It's also the reverse order in which they're destroyed.
The issue is that a struct layout may have a semantic of it's own.
For instance the order of member matters for langage interop, for alignment (although
it can be mitigated with alignas) ; structure layout can have some implications in
how cache friendly it is.

I wonder if there is a way to decouple initialisation order from the structure layout
and if it has been considered by C++ comitee.

Share this post


Link to post
Share on other sites
Advertisement

Can you provide an example case where this would be an issue? In my experience data requiring specific alignment is POD. I know that's not a language rule, but I've never actually encountered this conflict in practice, so I'm curious to see such a case.

Share this post


Link to post
Share on other sites

You could use one member unions to force class members not to be implicitly initialized in the constructor. Then in the constructor body you can use placement new to initialize that member late. Then, if member field is not trivially copyable, you also need to provide a copy constructor, destructor, and assignment operator.

 

It's ugly, so only use this technique for measurable performance gain.

Share this post


Link to post
Share on other sites

The committee had to choose some rule for initialization order.  The chose the one that will work reliably under all situations:  with the presence of explicit initialization or without.    I suppose the could have gone with "in the order of explicit initialization except when some explicit initializers are missing in which case you fall back to member declaration order and except when there is non-virtual multiple inheritance with differing base class constructor calls and also not in plain-old-data copy constructors or any classes derived from them and, well, there is no guarantee about default copy operators ever doing the right thing any more" but my guess is they thought that might be a little more error-prone and liable to unexpected behaviour.

Share this post


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

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!