簡體   English   中英

在基類中使用std :: enable_shared_from_this

[英]Using std::enable_shared_from_this in base classes

我想要一個私有繼承自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 (whithin整個層次可見)或private明確(僅可見里面的類):

#include <memory>

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

問題出在Foo ,而不是Bar 以下程序給出相同的錯誤。

我認為您必須公開繼承自std::enable_shared_from_this<>

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM