samedi 30 septembre 2017

Passing unique_ptr

I need to pass a unique pointer to a derived class by reference to a function which accepts a reference to a unique pointer to the base class, like here:

#include <memory>

using namespace std;

class Base {};
class Derived : public Base {};

void foo(std::unique_ptr<Base>& d){}

int main()
{
    unique_ptr<Derived> b = make_unique<Derived>();
    foo(b);
}

  1. Why doesn't this code work? I checked out other posts like this one, and the answer seems to be "because C++ wants the types to match exactly", but why is that? What dangerous situation am I potentially creating?

  2. If I instead do this, it compiles:

    void foo(unique_ptr<Base>&& d){}
    foo(move(b));
    
    

    Is this a reasonable approach?

Aucun commentaire:

Enregistrer un commentaire