# Unity Dependency Injection in an Initialiser List

## Recommended Posts

I have a situation where there are RAII wrapper components, B and C, that have a dependency on another, shared, RAII wrapper, A. For some reason I have a specific use of these components in mind for which I only require to create all these objects at once and destroy them at once (a more complex use might see these objects having different lifetimes). As such I would like to write a higher level component that encapsulates these components and provides an interface to express this specific use. In order to function it will need to inject an A into a B and a C. If this specific use only required the components to exist for a one-off operation then we might write a function like so:
void do_something_useful(data info)
{
// all constructed here
A a(info);
B b(a);
C c(a);

// do something with them
impl(b, c);

// all destructed here
}
We're quite used to seeing code like this, the function controls their lifetime and forwards the work off. However it is not suitable for my purpose, the objects are stateful (Hmm, state-full? ... Full-of-state [smile]) and need to persist between calls in order for this operation to work properly. The next most obvious solution, therefore, is to use a class, D, and have its ctor/dtor control their lifetime and a member function to perform the operation:
class D
{
A a;
B b;
C c;

public:
D(data info) : a(info), b(a), c(a) { }
/* ~D() - no need for an explicit destructor */

void do_something_useful();
};
This looks fine and it works fine, but it has a subtle nuance, it relies on the order of construction of members in a class to operate correctly. This is well defined, it's the order they appear in the class definition (not the order they appear in the initialisation list!). This, to me, feels slightly wrong for some reason. Maybe it's my distrust of other people not knowing their construction rules or maybe it's because, generally, I/we don't usually expect that the order of data members actually matters in the slightest. I have tried to do some searching to find other examples and opinions of this, the best I have is a post by Antheus where he claims that such designs evolve naturally in C++ as consequence of applying the IOC pattern. My question is, how do other people feel about this? Thanks.

##### Share on other sites
I can't recall any specific case where I would depend on initialization order. In most cases I've encountered the dependency was always external.

It's just an issue with usual C++ complexity, at least the order is guaranteed.

Why not just change D to take A as constructor, whereas A is constructed from info?

If state matters, then copying might be an issue anyway. If it doesn't, then A could be implicitly constructed from info. And if there are other life-cycle issues, then it doesn't make sense to force such designs, and just allocate them differently.

##### Share on other sites
Quote:
 Original post by AntheusWhy not just change D to take A as constructor, whereas A is constructed from info?
Certainly, if we assume the proposal in my post is bad, then alternatives are fairly easy to produce:
D make_d(data info){    return D(A(info));}
This seems like a likely route.

I could also use pointer types to defer construction to D's constructor body and do it all in there explicitly, but on the heap. In theory it could be the case that B and C are default constructable and fast-swappable/assignable, although they're not here I'm saying.

##### Share on other sites
I just don't see what the big deal is. Do people you work with usually randomly reorder members in classes for no reason?

##### Share on other sites
Quote:
 Original post by SiCraneI just don't see what the big deal is. Do people you work with usually randomly reorder members in classes for no reason?

Unlike passing 'this', the examples above do not generate any warnings by the compiler (at least MSVC doesn't). Change the order for whichever, and dependent objects suddenly get garbage.

I've only needed this type of dependency on a handful of very top-level objects, where order is somewhat obvious, and members don't really change.

Elsewhere, I'd simply pass info to A, B and C. That avoids the problem altogether. As always, if the shoe doesn't fit...

##### Share on other sites
Quote:
 Original post by AntheusChange the order for whichever, and dependent objects suddenly get garbage.

Yes, I understand the technical part of the OP's question. That doesn't address what I asked: do people you work with usually randomly reorder members in classes for no reason?

##### Share on other sites
Quote:
 Original post by AntheusUnlike passing 'this', the examples above do not generate any warnings by the compiler (at least MSVC doesn't). Change the order for whichever, and dependent objects suddenly get garbage.

G++ will although at the present moment I can not remember which flag gives the warning :)

##### Share on other sites
Quote:
Original post by magic_man
Quote:
 Original post by AntheusUnlike passing 'this', the examples above do not generate any warnings by the compiler (at least MSVC doesn't). Change the order for whichever, and dependent objects suddenly get garbage.

G++ will although at the present moment I can not remember which flag gives the warning :)

struct X {        int x, y;        X () : y(0), x(0) {}};

main.cc: In constructor X::X()':main.cc:2: warning: X::y' will be initialized aftermain.cc:2: warning:   int X::x'main.cc:3: warning:   when initialized here`

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628298
• Total Posts
2981890
• ### Similar Content

• Hey there! My name is Cpaws and I compose music, sound effects and overall sound design for video games and film. I'm looking to work on a horror game mainly for fun and as an addition to my portfolio. I've used Unity & Wwise before for audio implementation.
If you're interested in working together, don't hesitate to contact me at cpawsmusic@gmail.com
Here's a few demo reels of my past projects:
Here's some snippets of some quick game music I've composed: https://soundcloud.com/cpawsmusic/sets/cpaws-video-game-film-music
Here's my portfolio/website: https://CpawsMusic.com/
E-mail: cpawsmusic@gmail.com

• My first mobile game made by unity

iphone: https://itunes.apple.com/us/app/aa-countdown/id1314223584?ls=1&mt=8

I appreciate every suggestion
• By Simplepg
• By Simplepg

• Who We Are
We are Forged Interactive, a small team of like-minded game developers with the sole purpose of making games we love! We're a team of artists, animators, programmers, level designers, writers, composers, producers, and other creative minds. We want to make games that you, the modern gamer want to play! We hope to build a community that enjoys our games as much as we love creating them. With your feedback and support we will be able to achieve that.

GAME NAME is a fun, action-packed army builder with unique characters, challenges and engaging levels. Set forth on an adventure to protect friends, family and countrymen from new adversaries. Once defeated your enemies turn coat and join you in your adventures. Players can enjoy a range of troops and abilities based on their gameplay style which become more important as maps introduce more challenging terrain, enemies and bosses. Strong orc knights, dangerous shamans, and even a dragon are out on the prowl. Knowing when to fight and when to run, and how to manage your army is essential. Your actions alone decide the fate of this world.

Previous Work by Team
Although we are working towards our first game as a team, our team members themselves have past experience in the industry.
This includes members who have worked on titles including:
Final Fantasy Kingsglaive, FIFA, Xcom 2 and Civilization.

Who are we looking for? 3D Modellers Concept Artists Marketing Specialists Level Designer

What do we expect? Reference work or portfolio. Examples what have you already done and what projects you have worked on academic or otherwise. The ability to commit to the project on a regular basis. If you are going on a two-week trip, we don't mind, but it would be good if you could commit 10+ hours to the project each week. Willingness to work with a royalty based compensation model, you will be paid when the game launches. Openness to learning new tools and techniques
What can we offer? Continuous support and availability from our side. You have the ability to give design input, and creative say in the development of the game. Shown in credits on websites, in-game and more. Insight and contacts from within the Industry.
Contact
If you are interested in knowing more or joining. Please email or PM us on Skype. Myself or Colin will reply to you within 48 hours.

E-mail: Recruitment@ForgedInteractive.com
Skype: ForgedInteractive

Regards,
David and Colin