有没有副本可以向下传播shared_ptr?

sum*_*ght 2 c++ shared-ptr downcast c++11

#include <memory>

struct a {};
struct b : public a {};

std::shared_ptr<b> get()
{
    std::shared_ptr<a> temp(new b);
    return std::static_pointer_cast<b>(temp); // atomic ref-count inc/dec
}
Run Code Online (Sandbox Code Playgroud)

据我所知,downcast shared_ptr的唯一方法是static_pointer_cast.但是,它只需要const引用并创建参数的下载副本.如果可能的话,我想避免复制,因为复制构造和shared_ptr的破坏意味着原子递增/递减操作.

有一些移动构造函数采用shared_ptr的其他实例,但它们不支持向下转换.

是否可以避免以符合标准的方式复制?

Mar*_*k B 5

不,没有办法避免副本.

这是因为std::shared_ptr<a>和之间没有继承关系std::shared_ptr<b>,所以你不能在它们之间任意转换.

如果你想获取传递给构造函数的指针的所有权(通过移动),为什么不使用unique_ptr呢?如果您没有获得所有权,请不要将其作为智能指针传递.