I have a base class and a derived class along with a function that returns a reference to the base class. Is it safe to use make_unique and then downcast the pointers?
I am trying to avoid a copy operation.
class Animal {}
class Dog : Animal {}
Animal GetAnimal() { ... }
Dog GetDog() {
Dog dog = *std::make_unique<Dog>( GetAnimal() );
return dog;
}
Or is there a more straightforward way?
EDIT:
Here is the actual code (which is pretty close to what I am showing above:
// Convert from (m)anaged to (u)nmanaged Title
Title Data::MarshalTitle(TitleMap ^mdefn) {
Title udefn = MarshalValue(mdefn);
return udefn;
}
and then MarshalValue is defined as:
Value Data::MarshalValue(TitleMap ^mdefn)
Now, what you don't see here is that Value is a base class and Title is a derived class.
The error I get from the compiler is:
error C2440: 'initializing' : cannot convert from 'Definitions::Value' to 'Definitions::Title' D:\Projects\Parsers\View.cpp
Intellisense tells me that there is no suitable user-defined conversion from Value to Title.
This however, gets through the compiler fine, but I am unsure if this is safe.
// Convert from (m)anaged to (u)nmanaged Title Dimension definition
Title Data::MarshalTitle(TitleMap ^mdefn) {
Title udefn = *std::make_unique<Title>(MarshalValue(mdefn));
return udefn;
}