【问题标题】:Using std::enable_shared_from_this in base classes在基类中使用 std::enable_shared_from_this
【发布时间】:2016-04-13 20:39:26
【问题描述】:

我想要一个从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);

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    为了不暴露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;
    };    
    

    【讨论】:

      【解决方案2】:

      问题出在Foo,而不是Bar。以下程序给出相同的错误。

      我认为你必须公开继承 std::enable_shared_from_this&lt;&gt;

      #include <memory>
      
      class Foo : private std::enable_shared_from_this<Foo>
      {
          //...
      };
      
      class Bar : public Foo
      {
          //...
      };
      
      int main()
      {
          //std::shared_ptr<Bar> spBar(new Bar);
          std::shared_ptr<Foo> spBar(new Foo);
          return 0;
      }
      

      【讨论】:

      • 有趣。所以没有办法启用shared_from_this 仅供私人使用?
      • 我确认 clang++ (3.5.0)、stdlib++ 和 libc++ 存在同样的问题
      猜你喜欢
      • 2020-06-28
      • 1970-01-01
      • 1970-01-01
      • 2014-03-15
      • 2017-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-26
      相关资源
      最近更新 更多