Dependency injection in C++

前端 未结 8 1601
囚心锁ツ
囚心锁ツ 2020-12-13 04:40

This is also a question that I asked in a comment in one of Miško Hevery\'s google talks that was dealing with dependency injection but it got buried in the comments.

<
相关标签:
8条回答
  • 2020-12-13 05:23

    This talk is about Java and dependency injection.

    In C++ we try NOT to pass RAW pointers around. This is because a RAW pointer have no ownership semantics associated with it. If you have no ownership then we don't know who is responsible for cleaning up the object.

    I find that most of the time dependency injection is done via references in C++.
    In the rare cases where you must use pointers, wrap them in std::unique_ptr<> or std::shared_ptr<> depending on how you want to manage ownership.
    In case you cannot use C++11 features, use std::auto_ptr<> or boost::shared_ptr<>.

    I would also point out that C++ and Java styles of programming are now so divergent that applying the style of one language to the other will inevitably lead to disaster.

    0 讨论(0)
  • 2020-12-13 05:23

    I've recently been bitten by the DI bug. I think it solves a lot of complexity problems, especially the automated part. I've written a prototype which lets you use DI in a pretty C++ way, or at least I think so. You can take a look at the code example here: http://codepad.org/GpOujZ79

    The things that are obviously missing: no scoping, no binding of interface to implementation. The latter is pretty easy to solve, the former, I've no idea.

    I'd be grateful if anyone here has an opinion on the code.

    0 讨论(0)
提交回复
热议问题