Search code examples
c++c++11moveunique-ptr

unique ptr and move semantics


I have the following question about unique pointers and the ownership transfer Assume the following

class Base
{
    Base()
    {
    }
    void foo(unique_ptr<Base> p)
    {
    }
};
void main()
{
    Base b;
    b.foo(std::unique_ptr<Base> p(new Base);
}

The above section of code creates a temporal unique pointer and I expected a compile error. But the code compiles. I expected the only valid function prototype to be the

 void foo(unique_ptr<Base> && p)

I am surprize that and the two signatures of the functions are valid. Could you please explain why the void foo(unique_ptr p) is valid when we pass an rvalue reference? Thank you


Solution

  • std::unique_ptr has an rvalue constructor, so you can construct one from an rvalue. Calling a function that takes a class type as an argument just requires that there be a 1-argument non-explicit constructor for that class1 that can construct the class type from the parameter supplied to the call.


    1This is not the only way to call such a function; there are other ways involving explicit conversion operators