将共享指针作为参数传递

如果我声明一个包装在共享指针中的对象:

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

然后我想把它作为一个参数传递给一个方法:

DoSomething(myClassObject);


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

以上是否只是简单地增加了 share _ pt 的引用计数,一切都很酷? 还是留下了一个迷途指针?

你还要这么做吗:

DoSomething(myClassObject.Get());


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

我认为第二种方法可能更有效,因为它只需要复制1个地址(相对于整个智能指针而言) ,但第一种方法似乎更具可读性,而且我不预期会突破性能限制。我只是想确保它不会有什么危险。

谢谢你。

86692 次浏览

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.

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.

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.

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.

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!!!