简体   繁体   English

make_shared 和抽象多态性

[英]make_shared and abstract polymorphism

Is there any way I can use make_shared instead of shared_ptr for abstract types?对于抽象类型,有什么方法可以使用make_shared而不是shared_ptr吗?

Example:例子:

#include <memory>
#include <vector>

class Foo
{
public:
    virtual void fooFunc() = 0;
};

class Bar : public Foo
{
public:
    void fooFunc() {};
};

int main()
{
    std::vector< std::shared_ptr<Foo> > vec;

    vec.push_back(std::shared_ptr<Foo>(new Bar()));
    //vec.push_back(std::make_shared<Foo>(new Bar())); //doesn't work because Foo is abstract

    return 0;
}

You may use a std::static_pointer_cast if you want to be explicitly mentioning the cast:如果您想明确提及演员表,您可以使用std::static_pointer_cast

int main()
{
    std::vector<std::shared_ptr<Foo>> vec;
    vec.push_back(std::static_pointer_cast<Foo>(std::make_shared<Bar>()));
}

But it also works without it:但它也可以在没有它的情况下工作:

vec.push_back(std::make_shared<Bar>());

Here's a demo showing the behaviour: Demo这是显示行为的演示Demo

I'd recommend not to use std::make_shared in combination with new .我建议不要将std::make_sharednew结合使用。 There is a performance concern here and in my opinion it's a good thing to avoid unbalanced new / delete s.这里有一个性能问题,在我看来,避免不平衡的new / delete是一件好事。

I ended up here because I didn't specify my inheritance as public.我最终来到这里是因为我没有将我的继承指定为公开的。 So I had:所以我有:

class Bar : Foo 

instead of:代替:

class Bar : public Foo 

Adding the public made shared_ptr<Foo> foo = make_shared<Bar>(...) work as expected添加公共使shared_ptr<Foo> foo = make_shared<Bar>(...)按预期工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM