Passing unique_ptr to functions
Solution 1:
In Modern C++ style, there are two keys concepts:
- Ownership
- Nullity
Ownership is about the owner of some object/resource (in this case, an instance of Device
). The various std::unique_ptr
, boost::scoped_ptr
or std::shared_ptr
are about ownership.
Nullity is much more simple however: it just expresses whether or not a given object might be null, and does not care about anything else, and certainly not about ownership!
You were right to move the implementation of your class toward unique_ptr
(in general), though you may want a smart pointer with deep copy semantics if your goal is to implement a PIMPL.
This clearly conveys that your class is the sole responsible for this piece of memory and neatly deals with all the various ways memory could have leaked otherwise.
On the other hand, most users of the resources could not care less about its ownership.
As long as a function does not keep a reference to an object (store it in a map or something), then all that matters is that the lifetime of the object exceeds the duration of the function call.
Thus, choosing how to pass the parameter depends on its possible Nullity:
- Never null? Pass a reference
- Possibly null? Pass a pointer, a simple bare pointer or a pointer-like class (with a trap on null for example)
Solution 2:
It really depends. If a function must take ownership of the unique_ptr, then it's signature should take a unique_ptr<Device>
bv value and the caller should std::move
the pointer. If ownership is not an issue, then I would keep the raw pointer signature and pass the pointer unique_ptr using get()
. This isn't ugly if the function in question does not take over ownership.
Solution 3:
I would use std::unique_ptr const&
. Using a non const reference will give the called function the possibility to reset your pointer.
I think this is a nice way to express that your called function can use the pointer but nothing else.
So for me this will make the interface easier to read. I know that I don't have to fiddle around with pointer passed to me.