boost::shared_ptr
有一个不寻常的构造函数
template<class Y> shared_ptr(shared_ptr<Y> const & r, T * p);
我有点不明白这会有什么用。基本上它与 r
共享所有权,但 .get()
将返回 p
。 不是 r.get()
!
这意味着你可以这样做:
int main() {
boost::shared_ptr<int> x(new int);
boost::shared_ptr<int> y(x, new int);
std::cout << x.get() << std::endl;
std::cout << y.get() << std::endl;
std::cout << x.use_count() << std::endl;
std::cout << y.use_count() << std::endl;
}
你会得到这个:
0x8c66008
0x8c66030
2
2
请注意,指针是独立的,但它们都声称 use_count
为 2(因为它们共享同一对象的所有权)。
所以,x
所拥有的int
只要x
or y<就存在
就在身边。如果我理解文档正确,第二个 int
永远不会被破坏。我已经通过以下测试程序确认了这一点:
struct T {
T() { std::cout << "T()" << std::endl; }
~T() { std::cout << "~T()" << std::endl; }
};
int main() {
boost::shared_ptr<T> x(new T);
boost::shared_ptr<T> y(x, new T);
std::cout << x.get() << std::endl;
std::cout << y.get() << std::endl;
std::cout << x.use_count() << std::endl;
std::cout << y.use_count() << std::endl;
}
这输出(如预期):
T()
T()
0x96c2008
0x96c2030
2
2
~T()
那么...这种不寻常的结构有什么用处,它共享一个指针的所有权,但在使用时行为就像另一个指针(它不拥有)。
最佳答案
当您想要共享一个类成员并且该类的一个实例已经是一个 shared_ptr 时,它很有用,如下所示:
struct A
{
int *B; // managed inside A
};
shared_ptr<A> a( new A );
shared_ptr<int> b( a, a->B );
他们共享使用次数和内容。这是内存使用的优化。
关于c++ - boost 的 shared_ptr(shared_ptr<Y> const & r, T * p) 是做什么用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1403465/