【发布时间】:2015-09-09 15:15:00
【问题描述】:
Scott Meyers 在他的著作Effective Modern C++ 中提到,不鼓励对数组使用shared_ptr,因为当转换为基类指针时,它会在类型系统中创建“漏洞”。
但是,可以通过以下方式从unique_ptr<T[]> 创建shared_ptr<T>
std::shared_ptr<D> pDerived = std::shared_ptr<D>(std::make_unique<D[]>(3)); // Create an array of 3 D's
上面的代码有潜在危险吗?如果稍后将pDerived 复制到pBase 中,是否存在陷阱?
std::shared_ptr<B> pBase = pDerived; // B is the base class for D
【问题讨论】:
-
重开是因为stackoverflow.com/q/30495941/981959只讲第一个问题,不上
shared_ptr<B>