2

Should/Can smart pointers be passed by reference in functions?

Ie:

void foo(const std::weak_ptr<bar>& x)
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
sazr
  • 24,984
  • 66
  • 194
  • 362
  • Can is easy to find out, may i ask why you think it shouldnt? – Borgleader Jan 02 '16 at 03:40
  • 1
    Possible duplicate of [How do I pass smart pointers into functions?](http://stackoverflow.com/questions/12519812/how-do-i-pass-smart-pointers-into-functions) – 5gon12eder Jan 02 '16 at 03:41
  • @5gon12eder: Nearly, but no cookie. This is can/should, that is how. – Deduplicator Jan 02 '16 at 03:47
  • @Deduplicator I think [Nicol Bolas's](https://stackoverflow.com/users/734069/nicol-bolas) [answer](https://stackoverflow.com/questions/12519812/how-do-i-pass-smart-pointers-into-functions/12520022#12520022) explains the “should” part very well. Don't you? The “can” part might be a different story but then again, it's the same answer as for any other type. – 5gon12eder Jan 02 '16 at 03:51
  • @5gon12eder: Well, I don't see how it addresses the case if ownership-transfer is really not meant. It is a nice answer for that question though. – Deduplicator Jan 02 '16 at 03:57
  • The additional explanation in [Emilio Garavaglia's](https://stackoverflow.com/users/924727/emilio-garavaglia) [answer](https://stackoverflow.com/questions/12519812/how-do-i-pass-smart-pointers-into-functions/12520014#12520014) might also be relevant. – 5gon12eder Jan 02 '16 at 03:59
  • @5gon12eder: Actually, Mark Ransom's answer is the one touching on this question. – Deduplicator Jan 02 '16 at 04:05
  • Another interesting reading http://herbsutter.com/2013/06/05/gotw-91-solution-smart-pointer-parameters/ – Jarod42 Jan 02 '16 at 12:02

2 Answers2

2

Of course you can pass a smart-pointer by const&.

There is also a reason to do so:
If the function accepting said smart-pointer is just a front for one accepting a raw (observing) pointer for manipulating the (potential) pointee.
Never force anyone to use a smart-pointer for anything but transfering / sharing ownership, they might not be managing it with the one you insist on.

In all other cases, using a smart-pointer implies transfer / sharing of ownership, and avoiding a cheap copy (just a test whether it owns anything and reference-counting, as well as two pointer copies) doesn't actually buy you anything.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • 1
    As a clarification: Writing `unshared_ptr` is easy (that pretends to be a shared ptr to something, but lies), as is wrapping a different smart pointer. The problem is that by taking particular semantics, you imply use of them, and fully obeying semantics can be impossible. – Yakk - Adam Nevraumont Jan 02 '16 at 05:51
0

No, if we are talking about std smart pointers. const T & can't transfer/share ownership, so raw non-owning T * is always better and more efficient.

Victor Dyachenko
  • 1,363
  • 8
  • 18