将子shared_pointer转换为父shared_pointer c ++ 14

问题描述 投票:0回答:2

将子共享指针向上转换为其父共享指针的正确方法是什么?我从苹果到水果的评论部分是我不清楚的地方。

class Fruit
{
};

class Apple : public Fruit
{
};

typedef std::shared_ptr<Fruit> FruitPtr;
typedef std::shared_ptr<Apple> ApplePtr;

int main()
{
    ApplePtr pApple = ApplePtr( new Apple() );

    FruitPtr pFruit = /* what is the proper cast using c++ 14 */
}
casting c++14
2个回答
1
投票

你可以使用std::static_pointer_cast,它完全符合你的要求:

class Fruit { };
class Apple : public Fruit { };

int main() {
  std::shared_ptr<Apple> pApple = std::make_shared<Apple>();
  std::shared_ptr<Fruit> pFruit = std::static_pointer_cast<Fruit>(pApple)
  return 0;
}

另外,我会避免直接构建一个shared_ptr。这样做或使用make_shared的权衡可以在this cppreference.com page上阅读。我也会像你一样避免使用类型定义ApplePtrFruitPtr,因为它可能会让读取代码的人感到困惑,因为没有迹象表明它们是共享指针而不是原始指针。


1
投票

您可以简单地使用隐式向上转换:

FruitPtr pFruit = pApple

如果你要添加断点,你可以注意到在这一行之后强引用计数器增加到2(我假设你想要发生这种情况)。

无关评论:更喜欢使用make_shared而不是自己调用new(请阅读Difference in make_shared and normal shared_ptr in C++,了解原因)

© www.soinside.com 2019 - 2024. All rights reserved.