Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 vs. using boost::shared_ptr?

Is there another common way of doing it? How does it compare to the two methods above?

like image 670
Jonathan Livni Avatar asked Apr 20 '11 15:04

Jonathan Livni


People also ask

What is shared_ptr?

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.

Are shared_ptr slow?

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%.


2 Answers

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.

like image 118
Mark Ransom Avatar answered Oct 02 '22 20:10

Mark Ransom


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.

like image 26
Nick Avatar answered Oct 02 '22 18:10

Nick