Passing shared pointers as arguments

76,045

Solution 1

I want to pass a shared pointer to a function. Can you help me with that?

Sure, I can help with you that. I assume you have some understanding of ownership semantics in C++. Is that true?

Yeah, I'm reasonably comfortable with the subject.

Good.

Ok, I can only think of two reasons to take a shared_ptr argument:

  1. The function wants to share ownership of the object;
  2. The function does some operation that works specifically on shared_ptrs.

Which one are you interested in?

I'm looking for a general answer, so I'm actually interested in both. I'm curious about what you mean in case #2, though.

Examples of such functions include std::static_pointer_cast, custom comparators, or predicates. For example, if you need to find all unique shared_ptr from a vector, you need such a predicate.

Ah, when the function actually needs to manipulate the smart pointer itself.

Exactly.

In that case, I think we should pass by reference.

Yes. And if it doesn't change the pointer, you want to pass by const reference. There's no need to copy since you don't need to share ownership. That's the other scenario.

Ok, got it. Let's talk about the other scenario.

The one where you share the ownership? Ok. How do you share ownership with shared_ptr?

By copying it.

Then the function will need to make a copy of a shared_ptr, correct?

Obviously. So I pass it by a reference to const and copy to a local variable?

No, that's a pessimization. If it is passed by reference, the function will have no choice but to make the copy manually. If it is passed by value the compiler will pick the best choice between a copy and a move and perform it automatically. So, pass by value.

Good point. I must remember that "Want Speed? Pass by Value." article more often.

Wait, what if the function stores the shared_ptr in a member variable, for example? Won't that make a redundant copy?

The function can simply move the shared_ptr argument into its storage. Moving a shared_ptr is cheap because it doesn't change any reference counts.

Ah, good idea.

But I'm thinking of a third scenario: what if you don't want to manipulate the shared_ptr, nor to share ownership?

In that case, shared_ptr is completely irrelevant to the function. If you want to manipulate the pointee, take a pointee, and let the callers pick what ownership semantics they want.

And should I take the pointee by reference or by value?

The usual rules apply. Smart pointers don't change anything.

Pass by value if I'm going to copy, pass by reference if I want to avoid a copy.

Right.

Hmm. I think you forgot yet another scenario. What if I want to share ownership, but only depending on a certain condition?

Ah, an interesting edge case. I don't expect that to happen often. But when it happens you can either pass by value and ignore the copy if you don't need it, or pass by reference and make the copy if you need it.

I risk one redundant copy in the first option, and lose a potential move in the second. Can't I eat the cake and have it too?

If you're in a situation where that really matters, you can provide two overloads, one taking a const lvalue reference, and another taking an rvalue reference. One copies, the other moves. A perfect-forwarding function template is another option.

I think that covers all the possible scenarios. Thank you very much.

Solution 2

I think people are unnecessarily scared of using raw pointers as function parameters. If the function is not going to store the pointer or otherwise affect its lifetime, a raw pointer works just as well and represents the lowest common denominator. Consider for example how you would pass a unique_ptr into a function that takes a shared_ptr as a parameter, either by value or by const reference?

void DoSomething(myClass * p);

DoSomething(myClass_shared_ptr.get());
DoSomething(myClass_unique_ptr.get());

A raw pointer as a function parameter does not prevent you from using smart pointers in the calling code, where it really matters.

Solution 3

Yes, the entire idea about a shared_ptr<> is that multiple instances can hold the same raw pointer and the underlying memory will only be freed when there the last instance of shared_ptr<> is destroyed.

I would avoid a pointer to a shared_ptr<> as that defeats the purpose as you are now dealing with raw_pointers again.

Solution 4

Passing-by-value in your first example is safe but there is a better idiom. Pass by const reference when possible - I would say yes even when dealing with smart pointers. Your second example is not exactly broken but it's very !???. Silly, not accomplishing anything and defeats part of the point of smart pointers, and going to leave you in a buggy world of pain when you try to dereference and modify things.

Share:
76,045
Steve H
Author by

Steve H

email: steve (dot) hazen @ gmail (dot) com

Updated on January 23, 2020

Comments

  • Steve H
    Steve H over 4 years

    If I declare an object wrapped in a shared pointer:

    std::shared_ptr<myClass> myClassObject(new myClass());
    

    then I wanted to pass it as an argument to a method:

    DoSomething(myClassObject);
    
    //the called method
    void DoSomething(std::shared_ptr<myClass> arg1)
    {
       arg1->someField = 4;
    }
    

    Does the above simply increment the shared_pt's reference count and everything is cool? Or does it leave a dangling pointer?

    Are you still supposed to do this?:

    DoSomething(myClassObject.Get());
    
    void DoSomething(std::shared_ptr<myClass>* arg1)
    {
       (*arg1)->someField = 4;
    }
    

    I think that the 2nd way may be more efficient because it only has to copy 1 address (as opposed to the whole smart pointer), but the 1st way seems more readable and I do not anticipate pushing performance limits. I just want to make sure there's not something dangerous about it.

    Thank you.

  • ildjarn
    ildjarn about 12 years
    If you need shared ownership, you need to pass by value, otherwise you're not actually sharing anything. If you don't need shared ownership, then don't pass a shared_ptr<> to begin with.
  • djechlin
    djechlin about 12 years
    @ildjarn - Unsure if I agree with this. Can you produce a case where passing by pointer makes sense and passing by reference doesn't in the first place?
  • ildjarn
    ildjarn about 12 years
    No one is advocating passing by pointer, if you mean raw pointer. Passing by reference if there is no ownership contention is certainly idiomatic. The point is, regarding shared_ptr<> specifically, that you must make a copy in order to actually share ownership; if you have a reference or pointer to a shared_ptr<> then you're not sharing anything, and are subject to the same lifetime issues as a normal reference or pointer.
  • David Rodríguez - dribeas
    David Rodríguez - dribeas about 12 years
    @ildjarn: Passing a constant reference is fine in this case. The original shared_ptr of the caller is guaranteed to outlast the function call, so the function is safe in using the shared_ptr<> const &. If it needs to store the pointer for a later time, it will need to copy (at this point a copy must be made, rather than holding a reference), but there is no need to incur the cost of copying unless you need to do it. I would go for passing a constant reference in this case....
  • ildjarn
    ildjarn about 12 years
    @David : "Passing a constant reference is fine in this case." Not in any sane API -- why would an API mandate a smart pointer type that it's not even taking advantage of rather than just taking a normal const reference? That's almost as bad as lack of const-correctness. If your point is that technically it isn't hurting anything, then I certainly agree, but I don't think it's the Right thing to do.
  • David Rodríguez - dribeas
    David Rodríguez - dribeas about 12 years
    ... if on the other hand, the function does not need to extend the lifetime of the object, then you can just remove the shared_ptr from the interface and pass a plain (const) reference to the pointed object.
  • David Rodríguez - dribeas
    David Rodríguez - dribeas about 12 years
    @ildjarn: Well, I consider it a good guideline, my company considers it a sane guideline (and there are really smart people working here), and heck, even Herb Sutter considers it a good idea [second day's talk in Going Native 2012]. He actually calls passing the shared_ptr by value a pessimization. Then again, everyone could be wrong :) C++11 and beyond -- slide 22
  • ildjarn
    ildjarn about 12 years
    @David : What if your API consumer isn't using shared_ptr<> to begin with? Now your API is really just a pain in the neck, as it forces the caller to pointlessly change their object lifetime semantics just to use it. I don't see anything worth advocating in that, other than to say "it isn't technically hurting anything." I don't see anything controversial about 'if you don't need shared ownership, don't use shared_ptr<>'.
  • David Rodríguez - dribeas
    David Rodríguez - dribeas about 12 years
    @ildjarn: I think I covered that in a previous comment, if there is no need to extend the lifetime (i.e. no copies of the shared_ptr will be taken) then pass a plain reference. But, from your first comment: If you need shared ownership, you need to pass by value, otherwise you are not actually sharing anything is false, you need to pass the shared pointer by const-reference and then make a copy. Note that the lifetime of the parameter of the function (i.e. the copy in pass-by-value) will never outlast the lifetime of the original shared_ptr, so the extra copy is unneeded.
  • ildjarn
    ildjarn about 12 years
    @David : "I think I covered that in a previous comment" Agreed, I was (probably needlessly) re-ephmasizing. "... you need to pass by const-reference to the shared pointer and then make a copy." This makes no sense -- how is this semantically any different than passing by value, other than to make it possible for the caller to relinquishing ownership by moving (which is a good thing)? EDIT: misunderstood your last sentence.
  • David Rodríguez - dribeas
    David Rodríguez - dribeas about 12 years
    @ildjarn: let us continue this discussion in chat, but basically you are paying the cost of an atomic increment and gaining nothing out of it.
  • Xeo
    Xeo about 12 years
    If you're using a pointer, why not just use a reference? DoSomething(*a_smart_ptr)
  • Mark Ransom
    Mark Ransom about 12 years
    @Xeo, you're right - that would be even better. Sometimes you need to allow for the possibility of a NULL pointer though.
  • sbi
    sbi about 12 years
    @Jon: What for? This is all about should I do A or should I do B. I think we all know how to pass objects by value/reference, no?
  • Jon
    Jon about 12 years
    Because prose like "Does that mean I'll pass it by a reference to const to make the copy? No, that's a pessimization" is confusing to a beginner. Passing by a reference to const does not make a copy.
  • curiousguy
    curiousguy almost 12 years
    @DavidRodríguez-dribeas Note that if it is guaranteed that you will need to copy a parameter, pass by value is an optimisation over pass by reference, so that the copying is part of the public interface.
  • David Rodríguez - dribeas
    David Rodríguez - dribeas almost 12 years
    @curiousguy: That is less of an issue for types with reference semantics. In particular, there are limited cases where you will want to copy (store it in a member?) as the copy and the original are the same object. Even then, you would need to take the argument by value and explicitly move inside the function (again, the destination of the copy will never be a local variable to the function).
  • curiousguy
    curiousguy almost 12 years
    @DavidRodríguez-dribeas "there are limited cases where you will want to copy" If you do not want to copy, you probably do not need a smart ptr as a parameter.
  • David Rodríguez - dribeas
    David Rodríguez - dribeas almost 12 years
    @curiousguy: Unless you want to obtain a weak_ptr, for example. Discussing corner cases does not really make sense. I already mentioned before that changing the signature to take a reference instead of a smart pointer might be the way to go...
  • Kev
    Kev almost 12 years
    Can we move this discussion to here: chat.stackoverflow.com/rooms/11966/…
  • Andreas Magnusson
    Andreas Magnusson almost 12 years
    If you have a convention of using raw pointers as output parameters it's easier to spot in calling code that a variable may change, e.g.: compare fun(&x) to fun(x). In the latter example x could either be passed by value or as a const ref. It will as stated above also allow you to pass nullptrif you're not interested in the output...
  • radman
    radman over 11 years
    @Martinho I disagree with the rule "If you want to manipulate the pointee, take a pointee,". As stated in this answer not taking temporary ownership of an object can be dangerous. In my opinion the default should be to pass a copy for temporary ownership to guarantee object validity for the duration of the function call.
  • R. Martinho Fernandes
    R. Martinho Fernandes over 11 years
    @radman No scenario in the answer you link to applies that rule, so it's completely irrelevant. Please write me a SSCCE where you pass by reference from a shared_ptr<T> ptr; (i.e. void f(T&), called with f(*ptr)) and the object does not outlives the call. Alternatively write one where you pass by value void f(T) and trouble strikes.
  • radman
    radman over 11 years
    @Martinho check out my example code for the simple self contained correct example. The example is for void f(T&) and involves threads. I think my issue is that the tone of your answer discourages passing ownership of shared_ptr's, which is the safest, most intuitive and least complicated way of using them. I would be extremely against ever advising a beginner to extract a reference to data owned by a shared_ptr<> the possibilities for misuse are great and the benefit is minimal.
  • R. Martinho Fernandes
    R. Martinho Fernandes over 11 years
    The problem in your example is of a different nature: you have threads sharing the object but don't give them shared ownership. Read this answer clearly and you will realize that if you need to share ownership, you pass a shared_ptr. I think my answer encourages not finding one whateverst way of doing anything, and instead encourages thinking about what the heck you're trying to do. I don't want beginners (or anyone) to use smart pointers without understanding the idea of ownership.
  • R. Martinho Fernandes
    R. Martinho Fernandes over 11 years
    @radman Also note how your example passes the reference to std::ref, and the object does indeed outlive the call to std::ref.
  • R. Martinho Fernandes
    R. Martinho Fernandes over 11 years
    Having one thread pull the rug from under another thread will cause you trouble regardless of what you pass (what if the main() thread mutated the object?). It's completely unrelated to shared_ptr. It's an issue that only comes up when wanting to write multithreaded code without thinking.
  • radman
    radman over 11 years
    @Martinho It is not unrelated, if the function took a shared_ptr<> then no crash would occur. shared_ptr<> guarantees that the data it holds remains valid regardless of threading concerns. The other major danger is that the function being passed the reference takes a copy and stores it beyond the life of the call, which would cause problems without threading. You are advocating trusting the called function/object with doing the right thing, there are no semantics preventing them. If a full shared_ptr<> is passed then it's on their own head if they want to violate the ownership explicitly.
  • R. Martinho Fernandes
    R. Martinho Fernandes over 11 years
  • Zan Lynx
    Zan Lynx over 10 years
    @AndreasMagnusson: That pointer-as-output-parameter convention can give a false sense of security when dealing with pointers passed in from another source. Because in that case the call is fun(x) and *x is modified and the source has no &x to warn you.
  • daaxix
    daaxix almost 9 years
    What about when you need to pass a derived type as a base type? This requires pointers correct?
  • daaxix
    daaxix almost 9 years
    nevermind, just read that references avoid the slicing issue.
  • James
    James over 7 years
    This answer was difficult to read. Do you have a succinct answer for passing a shared pointer into a function to be stored there for use through out the life of the object? Maybe I should just use standard pointers instead of shared_ptr? Basically I have objects that must refer to each other...
  • R. Martinho Fernandes
    R. Martinho Fernandes over 7 years
    @James "to be stored there for use through out the life of the object" is covered under "Wait, what if the function stores the shared_ptr in a member variable, for example?" Regarding the answer being difficult to read, can you tell me which parts I could improve? FWIW, I wrote this under the assumption that the reader already has some understanding of ownership semantics in C++; I wanted to focus on argument passing specifically, and not muddle it by explaining ownership as well.
  • Sridhar Thiagarajan
    Sridhar Thiagarajan over 4 years
    what if the function call outlives the scope of the caller? There is a possibility that the shared ptr's destructor has been called, and now the function will be trying to access deleted memory, resulting in UB
  • Mark Ransom
    Mark Ransom over 4 years
    @SridharThiagarajan that's impossible unless the function makes a copy of the pointer and saves it somewhere for reuse later. The calling code scope doesn't change until the called function returns.
  • Sridhar Thiagarajan
    Sridhar Thiagarajan over 4 years
    it could change if the function is called in a seperate thread, can't it?
  • Mark Ransom
    Mark Ransom over 4 years
    @SridharThiagarajan there is nothing in the question that implies multi-threading. I don't think shared_ptr is guaranteed safe in a multi-threaded environment either, so your problems are just beginning.
  • Sridhar Thiagarajan
    Sridhar Thiagarajan over 4 years
    I think it's good to note, regardless of whether the OP uses in a multi-threaded context.