我想要一个私有(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/