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 reference compared to using boost :: shared_ptr ?

Is there any other general way to do this? How does it compare with the two methods described above?

+8
c ++ pass-by-reference dependency-injection shared-ptr
source share
4 answers

This is your choice of how you want to control the lifetime of the object you enter. The overall architecture is likely to determine which choice makes the most sense. With reference, something at a higher level should control the lifetime of the object; with shared_ptr , the lifetime will be automatically controlled.

+5
source share

I used to use both methods.

The advantage of using a common pointer approach means that you can transfer ownership of nested dependencies to the consumer.

If you use a referential approach, then breaking the injectable dependencies is much more deterministic. That is, this happens after the completion of all processing in consumers.

+2
source share

I remember seeing a code that did this with unique_ptr (or maybe auto_ptr ). This seems to be better than "by reference": there is no need to control the ownership of the injected object. This can be faster than using shared_ptr : no reference counting is required. This can be more confusing, though: it involves transferring ownership, and auto_ptr has some pitfalls.

+2
source share

The question you need to ask yourself is: who owns the property? In a typical scenario, DI is a consumer entity. In this case, I would pass the raw pointer to the constructor and save it into something like unique_ptr . If ownership is divided or not clear, then of course use shared_ptr .

-one
source share

All Articles