The following code fails on MSVC11 with the error
cannot convert parameter 1 from 'std::unique_ptr<DerivedClass>' to 'std::unique_ptr<BaseClass>'
The code:
class BaseClass
{ };
class DerivedClass : public BaseClass
{ };
void MyFunction(std::unique_ptr<BaseClass> obj)
{ };
int main()
{
auto ptr = std::unique_ptr<DerivedClass>(new DerivedClass);
MyFunction(ptr); // fails, with error about cannot convert type
// MyFunction(std::move(ptr)); // This will work
}
As pointed out in the answers the reason is std::move is missing, but the error message confused me enough to post the question, so I’ve updated it so anyone who is similarly confused has the best chance of finding the answer.
Your error has nothing to do with up or down casting. You are attempting to copy
ptr, which is not allowed. If you passstd::move(ptr), the cast will be implicit and automatic, like a regular pointer.