How to pass std::unique_ptr around?
Asked Answered
C

4

111

I am having my first attempt at using C++11 unique_ptr; I am replacing a polymorphic raw pointer inside a project of mine, which is owned by one class, but passed around quite frequently.

I used to have functions like:

bool func(BaseClass* ptr, int other_arg) {
  bool val;
  // plain ordinary function that does something...
  return val;
}

But I soon realized that I wouldn't be able to switch to:

bool func(std::unique_ptr<BaseClass> ptr, int other_arg);

Because the caller would have to handle the pointer ownership to the function, what I don't want to. So, what is the best solution to my problem?

I though of passing the pointer as reference, like this:

bool func(const std::unique_ptr<BaseClass>& ptr, int other_arg);

But I feel very uncomfortable in doing so, firstly because it seems non instinctive to pass something already typed as _ptr as reference, what would be a reference of a reference. Secondly because the function signature gets even bigger. Thirdly, because in the generated code, it would be necessary two consecutive pointer indirections to reach my variable.

Chemistry answered 30/6, 2012 at 20:2 Comment(0)
C
123

If you want the function to use the pointee, pass a reference to it. There's no reason to tie the function to work only with some kind of smart pointer:

bool func(BaseClass& base, int other_arg);

And at the call site use operator*:

func(*some_unique_ptr, 42);

Alternatively, if the base argument is allowed to be null, keep the signature as is, and use the get() member function:

bool func(BaseClass* base, int other_arg);
func(some_unique_ptr.get(), 42);
Catlin answered 30/6, 2012 at 20:7 Comment(2)
This is nice, but cam you get rid of the std::unique_ptr for a std::vector<std::unique_ptr> argument?Toothpaste
@CiroSantilliOurBigBook.com if you only want to temporarily store a reference to E from std::unique_ptr<E>, then you can do std::vector<E*> (or reference wrapper). If the vector is supposed to take ownership, it should hold elements of type std::unique_ptr<E> and you would std::move them into itDenyse
A
49

The advantage of using std::unique_ptr<T> (aside from not having to remember to call delete or delete[] explicitly) is that it guarantees that a pointer is either nullptr or it points to a valid instance of the (base) object. I will come back to this after I answer your question, but the first message is DO use smart pointers to manage the lifetime of dynamically allocated objects.

Now, your problem is actually how to use this with your old code.

My suggestion is that if you don't want to transfer or share ownership, you should always pass references to the object. Declare your function like this (with or without const qualifiers, as needed):

bool func(BaseClass& ref, int other_arg) { ... }

Then the caller, which has a std::shared_ptr<BaseClass> ptr will either handle the nullptr case or it will ask bool func(...) to compute the result:

if (ptr) {
  result = func(*ptr, some_int);
} else {
  /* the object was, for some reason, either not created or destroyed */
}

This means that any caller has to promise that the reference is valid and that it will continue to be valid throughout the execution of the function body.


Here is the reason why I strongly believe you should not pass raw pointers or references to smart pointers.

A raw pointer is only a memory address. Can have one of (at least) 4 meanings:

  1. The address of a block of memory where your desired object is located. (the good)
  2. The address 0x0 which you can be certain is not dereferencable and might have the semantics of "nothing" or "no object". (the bad)
  3. The address of a block of memory which is outside of the addressable space of your process (dereferencing it will hopefully cause your program to crash). (the ugly)
  4. The address of a block of memory which can be dereferenced but which doesn't contain what you expect. Maybe the pointer was accidentally modified and now it points to another writable address (of a completely other variable within your process). Writing to this memory location will cause lots of fun to happen, at times, during the execution, because the OS will not complain as long as you are allowed to write there. (Zoinks!)

Correctly using smart pointers alleviates the rather scary cases 3 and 4, which are usually not detectable at compile time and which you generally only experience at runtime when your program crashes or does unexpected things.

Passing smart pointers as arguments has two disadvantages: you cannot change the const-ness of the pointed object without making a copy (which adds overhead for shared_ptr and is not possible for unique_ptr), and you are still left with the second (nullptr) meaning.

I marked the second case as (the bad) from a design perspective. This is a more subtle argument about responsibility.

Imagine what it means when a function receives a nullptr as its parameter. It first has to decide what to do with it: use a "magical" value in place of the missing object? change behavior completely and compute something else (which doesn't require the object)? panic and throw an exception? Moreover, what happens when the function takes 2, or 3 or even more arguments by raw pointer? It has to check each of them and adapt its behavior accordingly. This adds a whole new level on top of input validation for no real reason.

The caller should be the one with enough contextual information to make these decisions, or, in other words, the bad is less frightening the more you know. The function, on the other hand, should just take the caller's promise that the memory it is pointed to is safe to work with as intended. (References are still memory addresses, but conceptually represent a promise of validity.)

Appellant answered 18/6, 2014 at 15:37 Comment(0)
D
32

I agree with Martinho, but I think it is important to point out the ownership semantics of a pass-by-reference. I think the correct solution is to use a simple pass-by-reference here:

bool func(BaseClass& base, int other_arg);

The commonly accepted meaning of a pass-by-reference in C++ is like as if the caller of the function tells the function "here, you can borrow this object, use it, and modify it (if not const), but only for the duration of the function body." This is, in no way, in conflict with the ownership rules of the unique_ptr because the object is merely being borrowed for a short period of time, there is no actual ownership transfer happening (if you lend your car to someone, do you sign the title over to him?).

So, even though it might seem bad (design-wise, coding practices, etc.) to pull the reference (or even the raw pointer) out of the unique_ptr, it actually is not because it is perfectly in accordance with the ownership rules set by the unique_ptr. And then, of course, there are other nice advantages, like clean syntax, no restriction to only objects owned by a unique_ptr, and so.

Derringer answered 1/7, 2012 at 0:41 Comment(0)
S
-1

Personally, I avoid pulling a reference from a pointer/smart pointer. Because what happens if the pointer is nullptr? If you change the signature to this:

bool func(BaseClass& base, int other_arg);

You might have to protect your code from null pointer dereferences:

if (the_unique_ptr)
  func(*the_unique_ptr, 10);

If the class is the sole owner of the pointer, the second of Martinho's alternative seems more reasonable:

func(the_unique_ptr.get(), 10);

Alternatively, you can use std::shared_ptr. However, if there's one single entity responsible for delete, the std::shared_ptr overhead does not pay off.

Seriatim answered 10/3, 2017 at 22:23 Comment(2)
Are you aware that, in most ocasions, std::unique_ptr has zero overhead, right?Chemistry
Yes, I'm aware of it. That's why I told him about the std::shared_ptr overhead.Seriatim

© 2022 - 2024 — McMap. All rights reserved.