拷贝一个多态类可能会导致切片问题,为了解决这个问题,应覆盖一个虚clone函数,让他根据实际类型进行复制并返回一个到新对象的所有权的指针(std::unique_ptr),在派生类,通过使用所谓的协变返回类型来返回派生类型。
struct Base
{
Base() = default;
virtual ~Base() = default;
virtual std::unique_ptr<Base> Clone()
{
return std::make_unique<Base>();
}
virtual string GetName() const { return "Base"; }
protected:
Base(const Base&) = default;
Base& operator=(const Base&) = default;
};
struct Derived :public Base
{
Derived() = default;
std::unique_ptr<Base> Clone() override
{
return std::make_unique<Derived>();
}
virtual string GetName() const { return "Derived"; }
protected:
Derived(const Derived&) = default;
Derived& operator=(const Derived&) = default;
};
int main()
{
auto pBase = std::make_unique<Base>();
printf("pBase'name:%s\n",pBase->GetName().c_str());
auto pBase1 = pBase->Clone();
printf("pBase1'name:%s\n", pBase1->GetName().c_str());
std::unique_ptr<Base> pDerived = std::make_unique<Derived>();
printf("pDerived'name:%s\n", pDerived->GetName().c_str());
std::unique_ptr<Base> pDerived1 = pDerived->Clone();
printf("pDerived'name:%s\n", pDerived1->GetName().c_str());
system("pause");
return 0;
}
结果: