Dependency injection in C++

前端 未结 8 1599
囚心锁ツ
囚心锁ツ 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:10

    Based on my own experience, it is best to have clear ownership rules. For small concrete objects, it is best to use direct copy to avoid cross dependency.

    Sometimes cross dependency is unavoidable, and there is no clear ownership. For example, (m) A instances own (n) B instances, and certain B instances can be owned by multiple As. In this case, the best approach is to apply reference counting to B, in the way similar to COM reference counting. Any functions that take possession of B* must increase reference count first, and decrease it when releasing the possession.

    I also avoid using boost::shared_ptr as it creates a new type (shared_ptr and B* become two distinct types). I found that it brings more headaches when I add methods.

提交回复
热议问题