gpt4 book ai didi

c++ - shared_ptr 的隐式转换

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:19:23 26 4
gpt4 key购买 nike

我有两个类 U 和 T 的 shared_ptr,其中 T 是 U 的基数。

shared_ptr<U>做一个隐式转换是没有问题的至 shared_ptr<T> .但也可以从 shared_ptr<T> 进行转换至 shared_ptr<U>

我尝试了建议的解决方案:

class T {
public:
virtual ~T() {}
protected:
void fillData() = 0;
};

class Timpl : public T
{
public:
virtual ~Timpl() {}
protected:
virtual void fillData() = 0;
};

class U : public Timpl {
public:
virtual ~U() {}
protected:
virtual void fillData() {...} // fill
};

typedef shared_ptr<T> TPtr
typedef shared_ptr<U> UPtr


TPtr tp = std::make_shared<U>();
UPtr up = std::static_pointer_cast<U>(tp); //<-- error here :

错误:没有匹配函数来调用“static_pointer_cast(TPtr)”

注意:模板 std::__shared_ptr<_Tp1, _Lp> std::static_pointer_cast(const std::__shared_ptr<_Tp2, _Lp>&)

注意:模板参数推导/替换失败:

注意:“TPtr {aka boost::shared_ptr}”不是从“const std::__shared_ptr<_Tp2, _Lp>”派生的

此问题的解决方案:

混合std::shared_ptrboost::shared_ptr这不是个好主意。

最佳答案

是的,使用static_pointer_cast:

#include <memory>

struct T { virtual ~T() {} };
struct U : T {};

std::shared_ptr<T> pt = std::make_shared<U>(); // *pt is really a "U"

auto pu = std::static_pointer_cast<U>(pt);

还有一个匹配的 std::dynamic_pointer_cast,如果无法进行转换,它会返回一个空指针。

关于c++ - shared_ptr 的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19932629/

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