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?
The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.
Admittedly, the std::shared_ptr is about two times slower than new and delete. Even std::make_shared has a performance overhead of about 10%.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With