Passing shared pointers as arguments

C++C++11Shared PtrC++ Faq

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

> 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 - C++

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 - C++

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 - C++

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.

Solution 5 - C++

in your function DoSomething you are changing a data member of an instance of class myClass so what you are modifying is the managed (raw pointer) object not the (shared_ptr) object. Which means at the return point of this function all shared pointers to the managed raw pointer will see their data member: myClass::someField changed to a different value.

in this case, you are passing an object to a function with the guarantee that you are not modifying it (talking about shared_ptr not the owned object).

The idiom to express this is through: a const ref, like so

void DoSomething(const std::shared_ptr<myClass>& arg)

Likewise you are assuring the user of your function, that you are not adding another owner to the list of owners of the raw pointer. However, you kept the possibility to modify the underlying object pointed to by the raw pointer.

CAVEAT: Which means, if by some means someone calls shared_ptr::reset before you call your function, and at that moment it is the last shared_ptr owning the raw_ptr, then your object will be destroyed, and your function will manipulate a dangling Pointer to destroyed object. VERY DANGEROUS!!!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteve HView Question on Stackoverflow
Solution 1 - C++R. Martinho FernandesView Answer on Stackoverflow
Solution 2 - C++Mark RansomView Answer on Stackoverflow
Solution 3 - C++R Samuel KlatchkoView Answer on Stackoverflow
Solution 4 - C++djechlinView Answer on Stackoverflow
Solution 5 - C++organicomanView Answer on Stackoverflow