Sign in to follow this  

Unity Dependency Injection in an Initialiser List

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

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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by Antheus
Why 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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by SiCrane
I 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 this post


Link to post
Share on other sites
Quote:
Original post by Antheus
Change 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 this post


Link to post
Share on other sites
Quote:
Original post by Antheus
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.

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

Share this post


Link to post
Share on other sites
Quote:
Original post by magic_man
Quote:
Original post by Antheus
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.

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 after
main.cc:2: warning: `int X::x'
main.cc:3: warning: when initialized here

Share this post


Link to post
Share on other sites

This topic is 3051 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.

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  

  • Similar Content

    • By Redlime
      I am a game development student working on a 2.5D beat 'em up brawler game in Unity as my final year project and I've been working on the ai for the enemies in the game. However, I've been unable to get the enemies to working properly as the enemies would be constantly stuttering and jerking while trying to follow the player. I've created a foreach statement and added some conditions that call for the robots to spread out and stay away from the player if it is not in an engaging enum state. This has been an issue plaguing the ai for a while now, analysing the animator, it seems like the robot's movement is instantaneously stopping and going which might be the reason causing this stuttering. But I'm not sure how to prevent the robot's movement from stopping and going. If anyone knows the reason why this is happening to the robots it would be much appreciated as my project is due soon and I'm still unable to fix such a game breaking bug! I've included a few videos below showing what is happening to my robots and also the stuttering shown inside the animator. I've also included the full script for my robots.
       
      Robots Stuttering
      Robots Stuttering Animator
      Robot.cs
    • By red1m3n
      Hi I'm a hobbyist getting together a team to pursue game creation, we'll do both 2D and 3D games, we would definitely build different types of games, and hopefully have a great time doing it. you dont have to have much experience, just enough that you think you can fill the position. I have plenty of ideas for games that I'd love your help with, and am completely open to fulfilling your game ideas . As of right now this is a for fun project thing, but if me and my team are satisfied with our work it can be published to steam or other platforms. 
      The positions I'm currently looking to fill are:
      2D Pixel artist
      3D Modeler 
      C# programmer
      Musician/Sound engineer
      I am currently working on a project it is a 2D Merchant adventure game with survival elements. It does not have a name yet, that's because I'm bad with names. 
       
      If interested please feel free to leave me a PM or email at dealtavu@gmail.com so we can talk more about it..
    • By Aggrojag
      Hello!
      I'm working on a game that is quite personal to me. It touches on my own depression, obsessions, phobias, etc. It's a narrative driven dark comedy with some small aspects of platforming and puzzle solving. The project is rather small as well. It touches on topics such as suicide, mental illness, family, corruption, free-will, and redemption.
      First, I'm looking for a 2D animator that can compliment the style of the attached image. The player character's animations will be a bit more extensive than a typical platformer. There will be many death animations, and some other strange dealings with the character that will need animation. Other items will include some objects in the world that are in need of animation. All static pieces of art will be handled by the artist that drew the attached image.
      Second, I'm looking for a male voice actor. There will be at minimum two characters that will need to be brought to life through vocals. They are a very core part of the game, though they will never be shown on screen. As a reminder, this is a rather dark comedy, so be prepared for some insanity in your portrayal of these characters. The first voice is that of a game show host's voice, while the other will be a devilish voice (without SFX, I think it cheapens it, does not necessarily need to be a low voice, this is more about the portrayal than how the voice sounds).
      Last, I would love to have an editor on board. More than just avoiding disaster in the writing, I'm looking for someone that can elevate it. There is not a ton of writing that will be in the final project, but it's important enough of an aspect to be trying to bring someone in to help with it.
      To those interested:
      I have a crappy prototype that exists, along with a couple game design docs. More than anything, I'd like to present the project through a voice chat via discord to any interested. Discord - Bobdul Thundercuck#4590
      I do plan to post this on itch.io and wherever else I can put it that makes sense. I fully expect to make nothing off this project, as should you. However, in the case that money is made, a rev share model will be in place.

       
      Edit: Editor position has been filled, title has been changed to reflect this, and crossed out the section detailing this.
    • By William Edmeades
      Hey guys and girls,   Have you ever found yourself trying to apply for a job to be a game developer or a game artist? Maybe a sound engineer or a script writer? Only to not even get an interview due to lack of ‘experience’, teamwork projects or released game titles you have worked on? I have for sure. The game industry is hard and competitive to get into for someone new, especially when you might have a full time job or even have to support a family. So I have come up with an idea and I wanted to throw something out there to see if people could be interested in such an idea.   What if you could be part of a virtual game development company? A place where you can work on projects with a team of people from the internet, soon to be known as your colleagues, which could be from anywhere in the world all working at your own pace when you have time to do as little or as much as you want.   The idea is we can create the power of a company and release titles together. Not only do you then have a released game title you have worked on under your resume, but also work experience, team work skills, and the power of helping each other and learning from each other.    My dream idea is to create a solid place for people to join a party and develop ideas and create games and level up it experience points.   As far as money is concerned, the games would either be released for free or any money would go towards charity, it’s not about making money, it’s about building a career or justness having fun building games and socialising with like minded people.    I want to make something amazing, I think it would benefit me, and I think others who are serious would benefit greatly too.   I await your critasism on the ‘prototype’ idea, I just wanted to see how many people would be interested in such a concept. And if you are very much into the idea, let’s make it happen.   Thanks,   Will. www.feelingterrible.com
    • By NDraskovic
      Hey guys,
      Like the title says, I'm trying to find out if it's possible to automatically set which scenes will be built for different platforms. For instance, I have scenes that I want to include when building for PC, but exclude them for mobile platforms. Is it possible to do this automatically (by some settings file, or by coding some editor extension), or do I have to manually (de)select them each time I switch platforms?
      Google just keeps sending me to the documentation sites about the regular publishing, but I can't find information about this problem.
      Thanks in advance
  • Popular Now