How do I pass smart pointers into functions?

27,664

Solution 1

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.

Solution 2

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, so if you must pass it you must pass a reference.

Solution 3

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).

Solution 4

  • 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.

Share:
27,664

Related videos on Youtube

Trevor Hickey
Author by

Trevor Hickey

and programming

Updated on July 20, 2022

Comments

  • Trevor Hickey
    Trevor Hickey almost 2 years

    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.

  • Nicol Bolas
    Nicol Bolas over 11 years
    "pssign as smartptr<T>&& (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.
  • Emilio Garavaglia
    Emilio Garavaglia over 11 years
    @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 ...
  • Nicol Bolas
    Nicol Bolas over 11 years
    -1: factual error: "passign as smartptr<T> (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.
  • Emilio Garavaglia
    Emilio Garavaglia over 11 years
    @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.
  • Nicol Bolas
    Nicol Bolas over 11 years
    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
    Nicol Bolas over 11 years
    -1: factual error: "so if you must pass it you must pass a reference." You can move into the parameter.
  • Mihai Todor
    Mihai Todor over 11 years
    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?
  • Nicol Bolas
    Nicol Bolas over 11 years
    @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.
  • Emilio Garavaglia
    Emilio Garavaglia over 11 years
    @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.
  • Mihai Todor
    Mihai Todor over 11 years
    Oh, I see... So how would this work in practice? If you have something like this std::unique_ptr<int> x = ...; doSomenthing(x);, what would x contain after the call to doSomenthing(x), which, presumably, invokes x's move constructor?
  • Nicol Bolas
    Nicol Bolas over 11 years
    @MihaiTodor: It would have to be doSomenthing(std::move(x));; you can't move an lvalue implicitly.
  • Rost
    Rost over 11 years
    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());.
  • GManNickG
    GManNickG over 8 years
    @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.
  • Deduplicator
    Deduplicator over 8 years
    @GManNickG: You are assuming that the smart-pointer cannot validly be nullptr. Even though that might make loads of sense...
  • GManNickG
    GManNickG over 8 years
    @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.
  • Deduplicator
    Deduplicator over 8 years
    @NicolBolas: But if it is moved, the object will be destroyed, which would be an error.
  • Deduplicator
    Deduplicator over 8 years
    @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?
  • Nicol Bolas
    Nicol Bolas over 8 years
    @Deduplicator: See my post on how you pass smart pointers around. Or more importantly, how you don't.
  • Nicol Bolas
    Nicol Bolas over 8 years
    @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.
  • Deduplicator
    Deduplicator over 8 years
    @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.
  • Nicol Bolas
    Nicol Bolas over 8 years
    @Deduplicator: I took exception to the implication that you cannot pass unique_ptr by value because it "can't be copied".
  • Mark Ransom
    Mark Ransom over 8 years
    @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.