Suppose I have an object which is managed by an std::unique_ptr
. Other parts of my code need to access this object. What is the right solution to pass the pointer?
Since the question update, I'd prefer:
std::reference_wrapper<>
as suggested by Richard Hodges, so long as you don't require the option of NULL values.
Note that your use case does seem to require a default constructor though, so this is out unless you have some public static instance to use as default.
some custom not_your_pointer
type with the required semantics: default-constructable, copyable and assignable, convertible from unique_ptr
and non-owning. Probably only worthwhile if you're using it a lot though, since writing a new smart pointer class requires some thought.
if you need to handle dangling references gracefully, use std::weak_ptr
and change ownership to a shared_ptr
(That is, only one shared_ptr exists: there's no ambiguity about ownership and object lifetime is unaffected)
Before the question update, I preferred:
indicate that ownership is not transferred by passing a reference:
void foo(T &obj); // no-one expects this to transfer ownership
called as:
foo(*ptr);
you do lose the ability to pass nullptr
though, if that matters.
indicate that ownership is not transferred by explicitly prohibiting it:
void foo(std::unique_ptr const &p) {
// can't move or reset p to take ownership
// still get non-const access to T
}
this is clear, but does expose your memory management policy to the callee.
pass a raw pointer and document that ownership should not be transferred. This is the weakest and most error prone. Don't do it.