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);
}
-
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?
-
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