Is dependency injection useful in C++

前端 未结 5 1461
暗喜
暗喜 2021-01-31 02:39

C# uses Dependency Injection (DI) a lot to have a lossless and testable platform. For this, I need

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 03:24

    Yes, dependency injection is useful in C++ as well. There is no reason why it shouldn´t be, because it doesn´t require a specific language or syntax, but just an object-oriented class architecture (at least this is probably the most usual case).

    While in C# there are only "pointers" to dynamically allocated objects, C++ has multiple variants, like "normal" local variables, multiple kind of pointers, references... additionally the concept of move semantics is very relevant to this.

    In C++ you're use a reference to an object, this is the way to use DI in C++, right?

    Not only. You can use whatever you want as long you can pass something to a class method and this something will exist as long as the class object does. All of the three possibilites above can do that (each of them with certain restrictions)

    is there something like a container were I can resolve all this references? In C# I've a "bad class/bad project/assembly" which register all my instance into a static container

    Maybe you´re missing the point of dependeny injection. It´s not the same as a bunch of "global" variables. But yes, of course this is possible in C++ too. There are classes, there is static, and that´s everything needed.

提交回复
热议问题