Hacker News new | ask | show | jobs
by lbrandy 2268 days ago
This is the only good use of a const& shared_ptr which is when you 1) only _might_ want to claim shared ownership of the thing, and 2) the perf of those unnecessary refcounts matter.

However, you missed a _super_ important caveat of this which is very subtle and very awful. And that is all of the code being executing here between the start of the function and the copy of the shared_ptr is doing it without the protection of the reference count on the shared pointer. It's entirely conceivable that, for example, the `has_widget` function, while executing, invalidates the original shared_ptr passed in and thus makes your eventual use of that shared_ptr invalid.

3 comments

I would assume the caller itself is holding on to the shared pointer.
True but that's bug-for-bug with passing a const&
How would it invalidate it?
Simple example:

    shared_ptr<int> global;
    void func(const shared_ptr<int>& v) {
        global.reset();
        *v += 1; // ohno
    }
    func(global);
fair enough, but that's fairly stupid programming :)

/* XXX the argument might be the same as the global value we're about to modify. API designers, eh? */

Doesn't have to be global - could be a member that gets modified in a callback, or that goes out of scope because something else gets deconstructed.

I'd also like to inquire as to what nontrivial codebase you've seen that contains no fairly stupid programming. I keep hearing about them, and trying to prove their existence, but so far I've collected more concrete evidence for the existence of bigfoot than I have for the existence of such codebases.

You would need to pass it across threads. At least that is all I can come up with.
that will not invalidate it. it might have other (negative) implications, but it does not invalidate it.
It doesn't automatically invalidate it, but it makes possible things that would invalidate it.
such as?
Other responses (different replies to grandparent) have examples.

More realisticly, if you pass a reference to a different thread and return there is no way when to know when the original goes out of scope. Don't do that.