Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>[update 1]</strong><br> If you can always guarantee the dependency outlives the addict, you <strong>can</strong> use a raw pointer/reference, of course. between these two, I'd make a very simple decision: pointer if NULL is allowed, reference otherwise. </p> <p>(The point of my original post was that neither pointer nor reference solve the lifetime problem)</p> <hr> <p>I'd follow the infamous google style guideline here, and use smart pointers.</p> <p>Both a pointer and a reference have the same problem: you need to make sure the dependency outlives the addict. That pushes a quite nasty responsibility onto the client.</p> <p>With a (reference-counted) smart pointer, the policy becomes <em>dependency is destroyed when noone uses it anymore</em>. Sounds perfect to me. </p> <p>Even better: with <code>boost::shared_ptr</code> (or a similar smart pointer that allows a type-neutral destruction policy) <em>the policy is attached to the object at construction</em> - which usually means everything affecting the dependency ends up in a single place.</p> <p>The typical problems of smart pointers - overhead and circular references - rarely come into play here. Dependency instances usually aren't tiny and numerous, and a dependency that has a strong reference back to its addicts is at least a code smell. (still, you need to keep these things in mind. Welcome back to C++)</p> <p>Warning: I am not "totally sold" to DI, but I'm totally sold on smart pointers ;)</p> <p><strong>[update 2]</strong><br> Note that you can always create a <code>shared_ptr</code> to a stack/global instance using a null deleter.<br> This requires both sides to support this, though: addict must make guarantees that it will not transfer a reference to the dependency to someone else who might live longer, and caller is back with the responsibility ensuring lifetime. I am not to happy with this solution, but have used this on occasion.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload