C++依赖注入 - 通过引用还是通过 boost::shared_ptr?
在需要构造函数依赖注入的情况下,使用通过引用注入与使用boost::shared_ptr相比有哪些注意事项?
还有另一种常见的方法吗?与上述两种方法相比如何?
In cases where constructor dependency injection is required, what are the considerations for using injection by reference vs. using boost::shared_ptr?
Is there another common way of doing it? How does it compare to the two methods above?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以选择如何管理所注入对象的生命周期。整体架构可能会决定哪种选择最有意义。通过引用,更高级别的东西必须管理对象的生命周期;使用
shared_ptr
,生命周期将被自动管理。It's your choice on how you want to manage the lifetime of the object you're injecting. The overall architecture will probably dictate which choice makes the most sense. With a reference, something at a higher level must manage the object lifetime; with
shared_ptr
the lifetime will be managed automatically.之前这两种方法我都用过。
使用共享指针方法的优点意味着您可以将注入依赖项的所有权传递给使用者。
如果您使用基于引用的方法,那么注入依赖项的破坏就更具确定性。即,一旦消费者中的所有处理完成,就会发生这种情况。
Previously I have used both methods.
The advantage of using the shared pointer approach means that you can pass ownership of the injected dependencies to the consumer.
If you use the reference based approach then destruction of the injected dependencies is much more deterministic. I.e. it occurs once all processing in the consumers has completed.
我记得看到过一些使用
unique_ptr
(或者可能是auto_ptr
)完成此操作的代码。这似乎比“通过引用”更好:不需要管理注入对象的所有权。这可能比使用shared_ptr
更快:不涉及引用计数。但这可能会更令人困惑:它涉及所有权转移,并且 auto_ptr 有一些陷阱。I remember seeing some code that did it with
unique_ptr
(or maybeauto_ptr
). This seems to be better than "by reference": there is no need to manage the ownership of the injected object. This might be faster than usingshared_ptr
: no reference counting is involved. This might be more confusing though: it involves transfer of ownership, andauto_ptr
has some pitfalls.您需要问自己的问题是:谁拥有该对象?在典型的DI场景中,它是消费者对象。在这种情况下,我会将原始指针传递给构造函数并将其存储到诸如
unique_ptr
之类的内容中。如果所有权是共享的或不清楚,那么当然可以使用shared_ptr
。The question you need to ask yourself is: who owns the object? In a typical DI scenario, it is the consumer object. In that case, I would pass a raw pointer to the constructor and store it into something like
unique_ptr
. If the ownership is shared or not clear, than of course, useshared_ptr
.