什么是Boost的shared_ptr的(shared_ptr的< Y>常量和放大器; R,T * P)用于? [英] What is boost's shared_ptr(shared_ptr<Y> const & r, T * p) used for?

查看:119
本文介绍了什么是Boost的shared_ptr的(shared_ptr的< Y>常量和放大器; R,T * P)用于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的boost :: shared_ptr的有一个不寻常的构造函数

boost::shared_ptr has an unusual constructor

template<class Y> shared_ptr(shared_ptr<Y> const & r, T * p);

和我一样是什么,这将是有用的有点摸不着头脑。基本上,它的股票所有权研究,但获得()将返回 P 不可以 r.get()

and I am a little puzzled as to what this would be useful for. Basically it shares ownership with r, but .get() will return p. not r.get()!

这意味着你可以做这样的事情:

This means you can do something like this:

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

,你会得到这样的:

And you will get this:

0x8c66008
0x8c66030
2
2

请注意,该指针是分开的,但它们都要求具有2的<​​code> use_count (因为它们共享同一个对象的所有权)。

Note that the pointers are separate, but they both claim to have a use_count of 2 (since they share ownership of the same object).

因此​​,由 X拥有 INT 会长期存在的 X 是各地。如果我理解正确的文档,第二个 INT 永远不会被破坏。我用下面的测试程序证实了这一点:

So, the int owned by x will exist as long as x or y is around. And if I understand the docs correct, the second int never gets destructed. I've confirmed this with the following test program:

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()

所以...什么是共享一个指针的所有权这个不寻常的结构的用处,但是使用时的作用像另一个指针(它不拥有)。

So... what is the usefulness of this unusual construct which shares ownership of one pointer, but acts like another pointer (which it does not own) when used.

推荐答案

当你想分享类成员和类的实例是很有用的已经是一个shared_ptr,如下所示:

It is useful when you want to share a class member and an instance of the class is already a shared_ptr, like the following:

struct A
{
  int *B; // managed inside A
};

shared_ptr<A>   a( new A );
shared_ptr<int> b( a, a->B );

他们共享使用计数和东西。它是内存使用的优化。

they share the use count and stuff. It is optimization for memory usage.

这篇关于什么是Boost的shared_ptr的(shared_ptr的&LT; Y&GT;常量和放大器; R,T * P)用于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆