2

Is there a modification to the interface that can get the second call to work?

Or should I leave things as is?

I suspect the extra construction in the first case was designed that way on purpose so it is clear that ownership is being transferred.

#include <memory>

struct Bar { };
typedef std::unique_ptr<Bar> UPBar;

void foo1( UPBar p ) {  }
void foo2( UPBar p ) { foo1( move( p )); }
void foo3( UPBar p ) { foo2( move( p )); }
void foo4( UPBar p ) { foo3( move( p )); }

int main(int argc, char** argv)
{
    UPBar p( new Bar );
    foo4( move( p ));  // ok, but requires an extra construction vs line below
    foo4( new Bar );   // fails: any modification to get this to work?

    return 0;
}

Second Question: If I change all the parameters passed to RValue-References (&&), is there any disadvantage in doing so? In fact, should I ensure that all my std::unique_ptr<> parameters are passed by RValue-References?

kfmfe04
  • 14,936
  • 14
  • 74
  • 140

1 Answers1

2

You can construct the unique_ptr as a temporary:

foo4( UPBar( new Bar ));

You can also write a make_unique function template, similar to the make_shared that exists for shared_ptr:

template <typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args) {
    return std::unique_ptr<T>(new T(std::forward<T>(args)...));
}

foo4( make_unique<Bar>() );
// other constructors are also callable:
foo4( make_unique<Bar>(x, y, z) );
R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
  • works great - tyvm. excellent second tip - ty. BTW, should I change all my fooX() functions to accept RHR/&& instead of passing-by-value? – kfmfe04 Dec 03 '11 at 07:05
  • 1
    @kfmfe04: no. Always take `unique_ptr`s by value. See this question: http://stackoverflow.com/questions/8114276/how-do-i-pass-a-unique-ptr-argument-to-a-constructor-or-a-function. I take the arguments by `&&` in this function because they're to be to forwarded to the constructor. – R. Martinho Fernandes Dec 03 '11 at 08:00