A simple code
class Base {}; class Derived : Base {}; unique_ptr<Base> Create() { unique_ptr<Base> basePtr = make_unique<Derived>(); // compile error return basePtr; } produce a compile error ("no suitable conversion"). I found similar question where the solution is to use std::move. I tried this
unique_ptr<Derived> derived = make_unique<Derived>(); unique_ptr<Base> basePtr = std::move(derived); // compile error but now std::move produces compile error. I also found question where (if I understood it well) the cast should be automatic if we use
unique_ptr<Base> basePtr = make_unique<Derived>(new Derived()); //compile error but this is also not working (compile error), and it is also not recommended to use new with smart pointers.
What would be the proper solution?
The only working solution I found so far
unique_ptr<Base> basePtr = unique_ptr<Base>((Base*)new Derived()); looks really ugly.