假设有以下这样的内容:
class Base {...};
class D1 : public Base {...};
class D2 : public Base {...};
在我的代码中,使用
std::shared_ptr<Base>
来管理类型为D1
和D2
的对象的生命周期并传递它们是否合法?或者这可能会导致一系列问题?假设有以下这样的内容:
class Base {...};
class D1 : public Base {...};
class D2 : public Base {...};
std::shared_ptr<Base>
来管理类型为D1
和D2
的对象的生命周期并传递它们是否合法?或者这可能会导致一系列问题?可以完全放心。智能指针被设计为可替换的裸指针。
当然,你需要考虑是否像使用裸指针一样使Base的成员函数virtual
。
Base* ptr_base = new Derived()
那么以下内容也应该是正确的
std::shared_ptr<Derived> ptr_derived = std::make_shared<Derived>();
std::shared_ptr<Base> ptr_base = ptr_derived;
// The shared pointer count is 2 as logically there are 2 handles to
// to the same memory object.
之后,基础共享指针就可以用于运行时多态,就像我们以前使用原始指针一样。
如果您的类是为多态性而设计的,则这样做是完全可以的。
如果您的类不是多态的(即没有虚成员),那么这个构造可能需要额外的工作(每个对象在调用成员函数时都将被处理为Base对象)。在这种情况下,最好使用std::shared_ptr<Base>
、std::shared_ptr<D1>
、std::shared_ptr<D2>
等,需要时使用static_pointer_cast<>
。