0

I'm implementing the Dependency Injection pattern in C++ with smart pointers. When using std::unique_ptr I'm wondering if there is any difference passing pointers in the constructor by rvalue reference or by value?

Should I use:

class SomeClass
{
public:
  SomeClass(std::unique_ptr<SomeInterface> someInterfaceInit) :
    someInterface{std::move(someInterfaceInit)}
  {}
private:
  std::unique_ptr<SomeInterface> someInterface;
};

or should I use rvalue reference:

class SomeClass
{
public:
  SomeClass(std::unique_ptr<SomeInterface>&& someInterfaceInit) :
    someInterface{std::move(someInterfaceInit)}
  {}
private:
  std::unique_ptr<SomeInterface> someInterface;
};

And second question is why I cannot omit std::move while using rvalue reference?

wsekta
  • 1
  • 1
  • 1
    You need `std::move` because `someInterfaceInit` is not an rvalue, despite being a rvalue reference. [See also](https://stackoverflow.com/questions/8114276/how-do-i-pass-a-unique-ptr-argument-to-a-constructor-or-a-function) – Nelfeal Jun 01 '23 at 10:18
  • `&&` is more like information for the caller (to be able perform proper overload resolution) then for internal use. Inside this is lvalue, outside it can be bound to rvalue. – Marek R Jun 01 '23 at 10:24

0 Answers0