C++ dependency injection - by reference or by boost::shared_ptr?
In cases where constructor dependency injection is required, what are the considerations for using injection by re开发者_Go百科ference vs. using boost::shared_ptr?
Is there another common way of doing it? How does it compare to the two methods above?
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.
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.
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
.
精彩评论