c++ - boost 的 shared_ptr(shared_ptr<Y> const & r, T * p) 是做什么用的?

标签 c++ boost shared-ptr smart-pointers

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/

相关文章:

c++ - 可以将共享指针与非指针数据成员混合使用吗?

c++ - 如何提高 C++ 中大数 (10^19) 的 pow 精度?

c++ - 对特定表单小部件实现 shift-click 修饰符?

c++ - "predefine"和使用命名空间和 std::shared_ptr 的正确方法是什么?

c++ - 在 Boost 中找不到共享库 (Linux Mint)

c++ - 关闭 boost asio ssl 套接字时需要调用 ssl::stream::shutdown 吗?

c++ - 我应该将有内存泄漏的库转换为 C++11 的智能指针吗?

c++ 各种数据类型的可变数组?

c++ - 为什么这个数组大小的模板不起作用?

python - 在 VS2013 中构建/包含 Boost.Python