Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 248
danny Avatar asked Nov 04 '22 14:11

danny


1 Answers

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.

like image 85
syplex Avatar answered Nov 15 '22 23:11

syplex