使用std :: shared_ptr和受保护的构造函数-析构函数 [英] using std::shared_ptr with a protected constructor\destructor

查看:249
本文介绍了使用std :: shared_ptr和受保护的构造函数-析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:


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.

我正在使用llvm 4.1,但我正在寻找一种解决方案,可以

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

这是代码示例:

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

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

};

有什么想法吗?

推荐答案

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

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.

这篇关于使用std :: shared_ptr和受保护的构造函数-析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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