0

Is it a bad usage to pass reference of a unique_ptr to the function?

void Foo(std::unique_ptr<T>& rT)
{
   ...
}
  • 1
    check this out http://stackoverflow.com/questions/9699333/passing-unique-ptr-to-functions – suraj_fale Mar 11 '13 at 03:47
  • 1
    Completely without context? Yes, it's bad. The unique pointer should only be exposed to those who care about the ownership of the managed object, which is rarely the case in code like yours. – Kerrek SB Mar 11 '13 at 03:47
  • Better to explain what it is you are actually doing, in detail, and ask whether you are using a good approach. – Nemo Mar 11 '13 at 03:48
  • What's the alternative? – n. m. could be an AI Mar 11 '13 at 03:49
  • 1
    What's your exact purpose here? If you are trying to give `Foo` access to what your `unique_ptr` points to, accept a `const T&` or in rare cases a `T&` (maybe for something like a swap function). If `Foo` should gain ownership, accept the `unique_ptr` by value. The caller of `Foo` can then `move` his `unique_ptr` to `Foo`. – David Mar 11 '13 at 03:51

1 Answers1

5

void Foo(std::unique_ptr<T>& rT) implies two things:

You cannot call the function like this: Foo(std::unique_ptr<T>(new T)); since it is a non-const lvalue reference. This restricts your function in only accepting lvalues.

If you pass an lvalue, you have no idea what happens to it: Foo(myunique_ptr);. In a call like this, you have no idea if Foo claims ownership of the std::unique_ptr. This can be dangerous if the caller is unaware of what happens inside of Foo and it is definitely not clear from the function signature.

Now after taking the above into consideration, you can decide whether it is bad usage or not.

Jesse Good
  • 50,901
  • 14
  • 124
  • 166