C++依赖注入 - 通过引用还是通过 boost::shared_ptr?

发布于 2024-11-02 06:23:54 字数 128 浏览 2 评论 0原文

在需要构造函数依赖注入的情况下,使用通过引用注入与使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

裂开嘴轻声笑有多痛 2024-11-09 06:23:54

您可以选择如何管理所注入对象的生命周期。整体架构可能会决定哪种选择最有意义。通过引用,更高级别的东西必须管理对象的生命周期;使用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.

橘香 2024-11-09 06:23:54

之前这两种方法我都用过。

使用共享指针方法的优点意味着您可以将注入依赖项的所有权传递给使用者。

如果您使用基于引用的方法,那么注入依赖项的破坏就更具确定性。即,一旦消费者中的所有处理完成,就会发生这种情况。

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.

橙幽之幻 2024-11-09 06:23:54

我记得看到过一些使用 unique_ptr (或者可能是 auto_ptr)完成此操作的代码。这似乎比“通过引用”更好:不需要管理注入对象的所有权。这可能比使用 shared_ptr 更快:不涉及引用计数。但这可能会更令人困惑:它涉及所有权转移,并且 auto_ptr 有一些陷阱。

I remember seeing some code that did it with unique_ptr (or maybe auto_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 using shared_ptr: no reference counting is involved. This might be more confusing though: it involves transfer of ownership, and auto_ptr has some pitfalls.

酒废 2024-11-09 06:23:54

您需要问自己的问题是:谁拥有该对象?在典型的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, use shared_ptr.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文