Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Depending on the context, either one could be fine. The main problem with returning a 'live' link to a member (if you have to expose one in the first place) is that whoever uses the exposed member is that your client might hold onto it longer than the containing object exists. And if your client accesses said member via a reference when its containing object goes out of scope, you'll be facing 'odd' crashes, wrong values and similar fun. Not recommended.</p> <p>Returning the weak_ptr&lt;> has the major advantage that it would be able to communicate to the client that the object they are trying access is gone, which the reference can't do.</p> <p>My 2 pennies' worth would be:</p> <ul> <li>If none of your clients would ever use the member, you as the author are the only person to make use of it and control the object lifetimes, returning a reference is fine. Const reference would be even better but that's not always possible in the real world with existing code.</li> <li>If anybody else would access and use the member, especially if you are writing a library, return the weak_ptr&lt;>. It'll save you a lot of grief and will make debugging easier.</li> <li>I would not return a shared_ptr&lt;>. I've seen this approach and it is usually favoured by people who are uncomfortable with the concept of a weak_ptr/weak reference. The main downside I see with it is that it will artificially extend the lifetime of another object's member beyond the scope of its containing object. That is conceptually wrong in 99% of cases and worse, can turn your programming error (accessing something that isn't there anymore) into a conceptual error (accessing something that <em>shouldn't</em> be there anymore).</li> </ul>
 

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