5

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?

4

1 回答 1

2

只需自己分配指针,而不是调用 make_shared:

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

但是请注意,这需要公开析构函数。

于 2012-10-16T18:01:06.470 回答