gpt4 book ai didi

c++ - 是否可以在没有拷贝的情况下向下转换 shared_ptr?

转载 作者:搜寻专家 更新时间:2023-10-31 00:39:13 25 4
gpt4 key购买 nike

#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
}

据我所知,向下转换 shared_ptr 的唯一方法是 static_pointer_cast。但是,它只接受 const 引用并创建参数的向下转换拷贝。如果可能的话,我想避免复制,因为 shared_ptr 的复制构造和销毁意味着原子递增/递减操作。

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

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

最佳答案

不,没有办法避免复制。

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

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

关于c++ - 是否可以在没有拷贝的情况下向下转换 shared_ptr?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16577832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com