28

When passing objects into functions, do the same rules apply to smart pointers as to other objects that contain dynamic memory?

When I pass, for example, a std::vector<std::string> into a function I always consider the following options:

  1. I'm going to change the state of the vector object, but I do not want those changes reflected after the function has finished, AKA make a copy.

    void function(std::vector<std::string> vec);
    
  2. I'm going to change the state of the vector object, and I do want those changes reflected after the function has finished, AKA make a reference.

    void function(std::vector<std::string> & vec);
    
  3. This object is pretty big, so I'd better pass a reference, but tell the compiler not to let me change it.

    void function(std::vector<std::string> const& vec);  
    

Now is this the same logic with smart pointers? And when should I consider move semantics? Some guidelines on how I should pass smart pointers is what I desire most.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • 3
    `unique_ptr` is non copiable, you'll have to make copies manually. `std::unique_ptr(mew T(*otherptr));` Other than that it should be the same as a vector. – Mooing Duck Sep 20 '12 at 19:47
  • 1
    See http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/ and http://stackoverflow.com/questions/8114276/how-do-i-pass-a-unique-ptr-argument-to-a-constructor-or-a-function – Dan Sep 20 '12 at 20:01
  • 1
    "*And what's the deal with move semantics?*" That's a completely different question, which has been asked and answered. – Nicol Bolas Sep 20 '12 at 20:04

4 Answers4

38

Smart pointers have pointer semantics, not value semantics (well, not the way you mean it). Think of shared_ptr<T> as a T*; treat it as such (well, except for the reference counting and automatic deletion). Copying a smart pointer does not copy the object it points to, just like copying a T* does not copy the T it points to.

You can't copy a unique_ptr at all. The whole point of the class is that it cannot be copied; if it could, then it wouldn't be a unique (ie: singular) pointer to an object. You have to either pass it by some form of reference or by moving it.

Smart pointers are all about ownership of what they point to. Who owns this memory and who will be responsible for deleting it. unique_ptr represents unique ownership: exactly one piece of code owns this memory. You can transfer ownership (via move), but in so doing, you lose ownership of the memory. shared_ptr represents shared ownership.

In all cases, the use of a smart pointer in a parameter list represents transferring ownership. Therefore, if a function takes a smart pointer, then it is going to claim ownership of that object. If a function isn't supposed to take ownership, then it shouldn't be taking a smart pointer at all; use a reference (T&) or if you have need of nullability, a pointer but never store it.

If you are passing someone a unique_ptr, you are giving them ownership. Which means, by the nature of unique ownership, you are losing ownership of the memory. Thus, there's almost no reason to ever pass a unique_ptr by anything except by value.

Similarly, if you want to share ownership of some object, you pass in a shared_ptr. Whether you do it by reference or by value is up to you. Since you're sharing ownership, it's going to make a copy anyway (presumably), so you might as well take it by value. The function can use std::move to move it into class members or the like.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 1
    So, just a stupid question: what happens if you pass a `unique_ptr` by value? Doesn't it *make a copy* of it, which violates it's uniqueness? Or perhaps you meant to say that `unique_ptr` should be passed only by reference? – Mihai Todor Sep 20 '12 at 20:17
  • @MihaiTodor: It *constructs* the value, but it doesn't necessarily use a *copy* constructor. If you `std::move` into it, or provide a temporary `unique_ptr`, it will use the move constructor, which does exist. – Nicol Bolas Sep 20 '12 at 20:18
  • Oh, I see... So how would this work in practice? If you have something like this `std::unique_ptr x = ...; doSomenthing(x);`, what would x contain after the call to `doSomenthing(x)`, which, presumably, invokes `x`'s move constructor? – Mihai Todor Sep 20 '12 at 20:23
  • 4
    @MihaiTodor: It would have to be `doSomenthing(std::move(x));`; you can't move an lvalue implicitly. – Nicol Bolas Sep 20 '12 at 20:28
  • 3
    I would not recommend to use dumb pointers even if the function doesn't take ownership. It's better to _always_ use smart pointers. Just pass them by `const&` if ownership is not affected. This will make your code more foolproof and avoid possibility to write something like `void f(T*); f(new T());`. – Rost Sep 20 '12 at 22:17
  • 2
    @Rost: +1 to avoiding naked pointers. However, in many cases how the object's lifetime is managed is irrelevant to the function. The function should just accept a `T&` and the caller can dereference if what they have is actually a (smart-)pointer. – GManNickG Jan 02 '16 at 03:56
  • @GManNickG: You are assuming that the smart-pointer cannot validly be `nullptr`. Even though that might make loads of sense... – Deduplicator Jan 02 '16 at 03:59
  • @Deduplicator: I am making no assumptions. If the caller has a null smart pointer, they can detect and handle this; the function should have no business in it. – GManNickG Jan 02 '16 at 04:01
  • @GManNickG: Correct me if I'm wrong, but you are saying that if the argument is `nullptr`, something is wrong, and the caller must handle that. But why do you assume there's something wrong, instead of that being a fully expected and valid input? – Deduplicator Jan 02 '16 at 04:07
  • 3
    @Deduplicator: OK, it's perfectly valid for some APIs to take a pointer which could be null. But quite frankly, it is *far* less common than the case where a function unquestionably needs a real object. Therefore, the general advice to prefer references where possible still ultimately stands. – Nicol Bolas Jan 02 '16 at 04:29
7

If the function isn't going to modify or make a copy of the pointer, just use a dumb pointer instead. Smart pointers are used to control the lifetime of an object, but the function isn't going to change the lifetime so it doesn't need a smart pointer, and using a dumb pointer gives you some flexibility in the type used by the caller.

void function(std::string * ptr);

function(my_unique_ptr.get());
function(my_shared_ptr.get());
function(my_dumb_ptr);

unique_ptr can't be copied without invalidating the original, so if you must pass it you must pass a reference.

For a more in-depth look at this recommendation by someone a lot smarter than me, see Herb Sutter's GotW #91 Solution: Smart Pointer Parameters. He goes beyond this recommendation and suggests that if the pointer can't be null, you should pass by reference instead of pointer. This requires dereferencing the pointer at the site of the call.

void function(std::string & val);

assert(my_unique_ptr != nullptr && my_shared_ptr != nullptr && my_dumb_ptr != nullptr);
function(*my_unique_ptr);
function(*my_shared_ptr);
function(*my_dumb_ptr);
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • 2
    -1: factual error: "*so if you must pass it you must pass a reference.*" You can move into the parameter. – Nicol Bolas Sep 20 '12 at 20:17
  • 1
    @NicolBolas: But if it is moved, the object will be destroyed, which would be an error. – Deduplicator Jan 02 '16 at 04:04
  • @Deduplicator: See my post on how you pass smart pointers around. Or more importantly, how you don't. – Nicol Bolas Jan 02 '16 at 04:24
  • 1
    @NicolBolas: Maybe I'm a bit slow today, but I'm not getting what you want to point out. The point of this answer seems to be that if the argument is just used for accessing the pointee instead of transfering ownership, requiring any smart-pointer-type would be far too cumbersome, and a raw (observing) pointer should be used instead. And your first comment says that one could instead move into a smart-pointer argument. Which would transfer ownership, and seems wrong to me. – Deduplicator Jan 02 '16 at 04:32
  • @Deduplicator: I took exception to the implication that you cannot pass `unique_ptr` by value because it "can't be copied". – Nicol Bolas Jan 02 '16 at 04:35
  • 1
    @NicolBolas it's true, you can't, unless you intend to change the ownership of the pointer. Read the first sentence of the answer for the qualifications on which it depends. – Mark Ransom Jan 02 '16 at 04:37
6

A smart pointer is an object that refer to another object an manages its lifetime.

Passing a smart pointer reuquires to respect the semantics the smart poitner support:

  • Passing as const smartptr<T>& always work (and you cannot change the pointer, but can change the state of what it points to).
  • Passing as smartptr<T>& always work (and you can change the pointer as well).
  • Passing as smartptr<T> (by copy) works only if smartptr is copyable. It works with std::shared_ptr, but not with std::unique_ptr, unless you "move" it on call, like in func(atd::move(myptr)), thus nullifying myptr, moving the pointer to the passed parameter. (Note that move is implicit if myptr is temporary).
  • Passing as smartptr<T>&& (by move) imposes the pointer to be moved on call, by forcing you to explicitly use std::move (but requires "move" to make sense for the particular pointer).
5gon12eder
  • 24,280
  • 5
  • 45
  • 92
Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63
  • 1
    "*pssign as smartptr&& (by move)*" && does not mean *move*. Using an r-value reference in a non-template deduced parameter argument means that the function can only be passed an expression that can bind to an r-value reference. So either a temporary or a `T&&` returned from a function. No actual movement happens until you construct an object. – Nicol Bolas Sep 20 '12 at 20:01
  • @NicolBolas: That's exactly my concept: "impose to be moved" by forcing to use std::move, otherwise the function does not bind. May be better if I reword ... – Emilio Garavaglia Sep 20 '12 at 20:05
  • 1
    -1: factual error: "*passign as smartptr (by copy) works only if smartptr is copyable*" This is not true at all. Pass by value works just fine for move-only types. You just have to move into the argument. – Nicol Bolas Sep 20 '12 at 20:07
  • @NicolBolas: please, understand the semantic of my answer follows the one of the question, not of the C++ specs, that use a reverse way to elaborate teh concept. As you said "Pass by value works just fine for move-only types. You just have to move into the argument." But after you did it, you haven't got a copy (there are no two equals pointers around). When I say *copy* I mean what the English dictionary (not the C++ specs) defines for *copy*. – Emilio Garavaglia Sep 20 '12 at 20:12
  • Then that's a -1 for misusing well-defined terminology. *Especially* since this is in the context of a discussion of C++ move and copy semantics. – Nicol Bolas Sep 20 '12 at 20:17
  • 1
    @NicolBolas: I cannot use "well defined terminology" with people that is not (yet) aware of it! I have to speak using normal day-to-day language, otherwise instead of text I have responded by writing code. If that's your taste, just keep it. But understand it is your "taste" against mine. There is no science behind it. I consider myself lucky in not having you as a teacher of mine. – Emilio Garavaglia Sep 20 '12 at 20:21
1
  • I know the person asked this question is more knowledgeable than me in C++ and There are some perfect answer to this question but I believe This question better be answer in a way that it doesn't scares people from C++, although it could get a little complicated, and this is my try:

Consider there is only one type of smart pointer in C++ and it is shared_ptr, so we have these options to pass it to a function:

1 - by value : void f(std::shared_ptr<Object>);

2 - by reference : void f(std::shared_ptr<Object>&);

The biggest difference is ,the First one lend you the ownership and The second one let you manipulate the ownership.

further reading and details could be at this link which helped me before.

malloc
  • 604
  • 10
  • 18