【发布时间】:2015-06-10 18:22:04
【问题描述】:
这是一个玩具示例,说明了我遇到的一个问题。该应用程序是相当不相关的(它本质上是一个元素的链接列表,最后具有特殊行为)。我无法使用派生指针构造基类 shared_ptr ,并且由于某种原因与我使用私有继承这一事实有关。
#include <iostream>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
using namespace std;
// An Item in a linked list
class A
{
public:
//friend class B;
typedef boost::shared_ptr<A> APtr;
A() : next_() {}
A(APtr n) : next_(n) {}
APtr next() { return next_; }
void setNext(APtr n) { next_ = n; }
virtual void doIt() { /* standard behavior */ }
private:
APtr next_;
};
class B : private A // B really is a special A
// that should have different behavior
// at the tail of the chain
// but I want to hide A's interface
// to external clients
{
public:
typedef boost::shared_ptr<B> BPtr;
B(A::APtr prev)
{ // Set this object as the tail
prev->setNext(APtr(this)); /* WHY CAN'T I CONSTRUCT APtr(this)
WITH PRIVATE INH. */
}
void doIt() {/*special behavior at end */}
};
int main()
{
A::APtr dummyPtr;
A::APtr head = boost::make_shared<A>(dummyPtr);
B::BPtr tail = boost::make_shared<B>(head);
for(A::APtr curr = head; curr; curr=curr->next()){
curr->doIt();
}
return 0;
}
我明白了
/usr/include/boost/smart_ptr/shared_ptr.hpp: In constructor ‘boost::shared_ptr<T>::shared_ptr(Y*) [with Y = B, T = A]’:
derived_shared.cpp:31: instantiated from here
/usr/include/boost/smart_ptr/shared_ptr.hpp:352: error: ‘A’ is an inaccessible base of ‘B’
我的印象是私有继承允许派生类仍然访问基类的公共接口,但将该接口隐藏给外部客户端。为什么私有继承会导致这个错误(如果我公开继承它会起作用)?
【问题讨论】:
-
你应该阅读这个页面stackoverflow.com/questions/860339/…
-
朋友 boost::shared_ptr,但你的设计有缺陷(传递非动态分配 B 的地址)
-
你应该看看enable_shared_from_this。
-
@DieterLücking 是的,你是对的......这只是我的玩具示例中的一个疏忽......对不起。所以我会让 boost::shared_ptr 成为 B 或 A 的朋友?
-
@innocent_bystander Dieter 的意思是(如果继承是公开的)head 被称为 shared_ptr 和 shared_ptr,两个不同的共享指针。离开 main 时,两个引用计数都变为 0,并尝试删除该对象两次。不应使用相同的原始指针来创建不同类型的共享指针。
标签: c++ inheritance shared-ptr