using std::shared_ptr with a protected constructor\destructor [duplicate]

白昼怎懂夜的黑 提交于 2019-12-22 06:10:26

问题


Possible Duplicate:
How do I call ::std::make_shared on a class with only protected or private constructors?

I want to create a shared pointer to a class, and have a factory method that returns it while keeping the constructor\destructor protected. since the shared pointer can't access the the constructor or the destructor, I get compiler errors.

I am using llvm 4.1, but I am looking for a solution that can be compiler independent (besides making the constructor\destructor public).

this is a code sample:

class Foo
{
public:
    static std::shared_ptr<Foo> getSharedPointer()
    {
        return std::make_shared<Foo>();
    }

protected:
    Foo(int x){}
    ~Foo(){}

};

any Ideas?


回答1:


Just allocate the pointer yourself instead of calling make_shared:

static std::shared_ptr<Foo> getSharedPointer()
{
    return std::shared_ptr<Foo>(new Foo);
}

Note, however, that this would require making the destructor public.



来源:https://stackoverflow.com/questions/12920609/using-stdshared-ptr-with-a-protected-constructor-destructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!