c++ - 在基类中使用 std::enable_shared_from_this

标签 c++ c++11

我想要一个私有(private)继承于 std::enable_shared_from_this<TBASE> 的基类。但是,当我尝试创建指向派生类中的对象的共享指针时,编译器会直接查找 std::enable_shared_from_this<TBASE> 中的构造函数。 ,因此失败,因为它是一个无法访问的基地。

下面的示例无法在 g++ 5.2.1 上编译

#include <memory>

class Foo : private std::enable_shared_from_this<Foo>
{
    //...
};

class Bar : public Foo
{
    //...
};

int main()
{
    std::shared_ptr<Bar> spBar(new Bar);
    return 0;
}

有没有办法可以在 Bar 内指定不要尝试使用无法访问的shared_ptr构造函数?

g++ 错误是:

In file included from /usr/include/c++/5/bits/shared_ptr.h:52:0,
             from /usr/include/c++/5/memory:82,
             from example.cxx:1:

/usr/include/c++/5/bits/shared_ptr_base.h: In instantiation of ‘std::__shared_ptr<_Tp, _Lp>::__shared_ptr(_Tp1*) [with _Tp1 = Bar; _Tp = Bar; __gnu_cxx::_Lock_policy _Lp = (__gnu_cxx::_Lock_policy)2u]’:

/usr/include/c++/5/bits/shared_ptr.h:117:32:   required from ‘std::shared_ptr<_Tp>::shared_ptr(_Tp1*) [with _Tp1 = Bar; _Tp = Bar]’

example.cxx:15:39:   required from here

/usr/include/c++/5/bits/shared_ptr_base.h:887:36: error: ‘std::enable_shared_from_this<Foo>’ is an inaccessible base of ‘Bar’
__enable_shared_from_this_helper(_M_refcount, __p, __p);

最佳答案

为了不暴露shared_from_this,您可以将其设置为protected(在整个层次结构中可见)或private(仅在类内部可见)明确:

#include <memory>

class Foo : public std::enable_shared_from_this<Foo>
{
private:
    using std::enable_shared_from_this<Foo>::shared_from_this;
};    

关于c++ - 在基类中使用 std::enable_shared_from_this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36597276/

相关文章:

c++ - 如何获得标准分类类型的 IClassifier?

c++ - 如何在不指定模板的情况下声明函数模板指针typedef?

c++ - 在 C++ 中拆分对象 vector

c++ - OpenCV drawContours 奇怪的行为

c++ - 自动参数捕获的推导规则是什么?

c++ - 如何使 std::make_pair 可与 std::bind* 一起使用?

c++ - 尝试使用模板函数交换两个字符串

c++ - 相互引用的C++模板实例化

c++ - 如何为基类泛型类型创建 vector 以使用具体类型元素

c++ - 为什么 unique_ptr::reset 没有带删除器的重载?