Tek
Tek

Reputation: 3050

how to pass unique_ptr with interfaces?

I just wondering why is it that I'm able to pass ownership and not a reference in the following code? I know using std::unique_ptr< car > pcar( new toyota() ); would let me pass the reference but why does this not apply to the ownership transfer?

#include <memory>

class car{};

class toyota : public car{};

void someProcess( std::unique_ptr< car > vehicle )
{
    //Ownership passed.
}

void otherProcess( std::unique_ptr< car > const & vehicle )
{
    //Reference passed.
}

int main( int argc, char ** argv )
{
    std::unique_ptr< toyota > pcar( new toyota() );

    someProcess( std::move( pcar ) ); //Allowed to pass through car interface.

    pcar.reset( new toyota() );

    otherProcess( pcar ); //Compiler error, can't pass reference even when car interface is implemented.

    return 0;
}

Upvotes: 3

Views: 2754

Answers (1)

Bwmat
Bwmat

Reputation: 4578

pcar is NOT a std::unique_ptr< car >. In order for that to compile, a temporary std::unique_ptr< car > would need to be created to bind to that argument. But you can't create a temporary since there's no (converting) constructor for unique_ptr that takes in an lvalue unique_ptr.

Basically, if that compiled, the temporary would be created, take ownership of the pointer, then be destroyed when the function returned, so the pointer owned by pcar would have been destroyed, not very intuitive nor desired behaviour.

Upvotes: 3

Related Questions