class A
{
public:
void test() { std::cout << "test" << std::endl; }
};
class B : public A
{
public:
void test2() { std::cout << "test2" << std::endl; }
};
std::unique_ptr<A> Get()
{
std::unique_ptr<A> b(new B);
return b;
}
int main()
{
auto o = Get(); // 如何转换为 std::unique_ptr<B> ?
system("pause");
return 0;
}
Direct conversion (downcasting/dynamic_cast) will cause errors.
You should first take out the pointer of dynamic type in unique_ptr b:
Then redefine a new unique_ptr, then release the original pointer and reset the new pointer:
stdout: