如何make_shared派生类? [英] How to make_shared a derived class?

查看:210
本文介绍了如何make_shared派生类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对派生类使用make_shared<T>函数,如下所示

I want to use the make_shared<T> function with a derived class, like below

class Base {
     public:
     typedef std::shared_ptr<Base> Ptr;
};

class Derived : public Base {};

Base::Ptr myPtr = std::make_shared(/* Derived() */ );

如何告诉make_shared构建这样的对象?

How can I tell make_shared to build such an object?

我想避免经典

Base::Ptr ptr = Base::Ptr(new Derived());

要在make_shared函数中使用单个alloc.

To make use of the single alloc in the make_shared function.

推荐答案

std::shared_ptr具有可以从shared_ptr<Derived>生成shared_ptr<Base>的转换构造函数,因此以下应该起作用:

std::shared_ptr has a converting constructor that can make a shared_ptr<Base> from a shared_ptr<Derived>, so the following should work:

#include <memory>
class Base {
    public:
    typedef std::shared_ptr<Base> Ptr;
};
class Derived : public Base {};

int main() {
    Base::Ptr myPtr = std::make_shared<Derived>();
}

这篇关于如何make_shared派生类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆