shared_ptr: 复制基数class的shared_ptr时引用计数会增加吗?
shared_ptr: Does the reference count increase when copying in a shared_ptr of the base class?
documentation of boost::shared_ptr 说:
shared_ptr<T>
can be implicitly converted to shared_ptr<U>
whenever T*
can be implicitly converted to U*. In particular, shared_ptr<T>
is
implicitly convertible to shared_ptr<T const>
, to shared_ptr<U>
where
U
is an accessible base of T
, and to shared_ptr<void>
.
但我没有找到任何地方写的,如果这样做,它会增加引用计数器。
我尝试了以下代码,it works:
struct A {
virtual int foo() {return 0;}
};
struct B : public A {
int foo() {return 1;}
};
int main() {
boost::shared_ptr<A> a;
{
boost::shared_ptr<B> b(new B());
a = b;
}
std::cout << a->foo() << std::endl; ///Prints 1
}
假设情况总是如此,但我找不到可以证实这一点的信息来源。
好的,当我写完问题时,我终于找到了答案,在copy constructor documentation
shared_ptr(shared_ptr const & r); // never throws
template<class Y> shared_ptr(shared_ptr<Y> const & r); // never throws
Requires: Y* should be convertible to T*.
Effects: If r is empty, constructs an empty shared_ptr;
otherwise, constructs a shared_ptr that shares ownership with r.
Postconditions: get() == r.get()
&& use_count() == r.use_count()
.
所以,答案是是。
documentation of boost::shared_ptr 说:
shared_ptr<T>
can be implicitly converted toshared_ptr<U>
wheneverT*
can be implicitly converted to U*. In particular,shared_ptr<T>
is implicitly convertible toshared_ptr<T const>
, toshared_ptr<U>
whereU
is an accessible base ofT
, and toshared_ptr<void>
.
但我没有找到任何地方写的,如果这样做,它会增加引用计数器。
我尝试了以下代码,it works:
struct A {
virtual int foo() {return 0;}
};
struct B : public A {
int foo() {return 1;}
};
int main() {
boost::shared_ptr<A> a;
{
boost::shared_ptr<B> b(new B());
a = b;
}
std::cout << a->foo() << std::endl; ///Prints 1
}
假设情况总是如此,但我找不到可以证实这一点的信息来源。
好的,当我写完问题时,我终于找到了答案,在copy constructor documentation
shared_ptr(shared_ptr const & r); // never throws template<class Y> shared_ptr(shared_ptr<Y> const & r); // never throws
Requires: Y* should be convertible to T*.
Effects: If r is empty, constructs an empty shared_ptr; otherwise, constructs a shared_ptr that shares ownership with r.
Postconditions:
get() == r.get()
&&use_count() == r.use_count()
.
所以,答案是是。