boost的shared_ptr(shared_ptr <Y> const&r,T*p)用于什么?

Eva*_*ran 26 c++ boost smart-pointers shared-ptr

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

template<class Y> shared_ptr(shared_ptr<Y> const & r, T * p);
Run Code Online (Sandbox Code Playgroud)

我对这对什么有用感到有些疑惑.基本上它与股份共享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;
}
Run Code Online (Sandbox Code Playgroud)

你会得到这个:

0x8c66008
0x8c66030
2
2
Run Code Online (Sandbox Code Playgroud)

请注意,指针是分开的,但它们都声称具有use_count2(因为它们共享同一对象的所有权).

因此,所int拥有的x将存在只要x 即将存在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;
}
Run Code Online (Sandbox Code Playgroud)

此输出(如预期):

T()
T()
0x96c2008
0x96c2030
2
2
~T()
Run Code Online (Sandbox Code Playgroud)

那么...是这股一个指针的所有权这个不寻常的结构的实用性,但行为上的相同另一个指针(它不拥有).

lei*_*eiz 29

当您想要共享一个类成员并且该类的实例已经是shared_ptr时,它非常有用,如下所示:

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

shared_ptr<A>   a( new A );
shared_ptr<int> b( a, a->B );
Run Code Online (Sandbox Code Playgroud)

他们分享使用数量和东西.它是内存使用的优化.


Mic*_*urr 8

为了扩展leizpiotr的答案,shared_ptr<>'别名'的描述来自WG21论文," shared_ptr针对C++ 0x进行改进,修订版2":

III.别名支持

高级用户通常需要能够创建与另一个(主)共享所有权的shared_ptr 实例p,shared_ptr q但指向不是其基础的对象*q.*p例如,可以是例如的成员或元素*q.本节提出了一个可用于此目的的附加构造函数.

这种表达能力增加的一个有趣的副作用是现在*_pointer_cast可以在用户代码中实现这些功能.make_shared本文档后面介绍的 工厂函数也可以仅使用shared_ptr通过别名构造函数的公共接口来实现.

影响:

此功能shared_ptr以向后兼容的方式扩展了接口 ,增加了其表达能力,因此强烈建议将其添加到C++ 0x标准中.它没有引入源和二进制兼容性问题.

拟议案文:

添加到shared_ptr [util.smartptr.shared]以下构造函数:

template<class Y> shared_ptr( shared_ptr<Y> const & r, T * p );
Run Code Online (Sandbox Code Playgroud)

将以下内容添加到[util.smartptr.shared.const]:

template<class Y> shared_ptr( shared_ptr<Y> const & r, T * p );
Run Code Online (Sandbox Code Playgroud)

效果:构造一个shared_ptr存储p共享所有权 的实例r.

后置条件: get() == p && use_count() == r.use_count().

抛出:没什么.

[注意:为了避免悬空指针的可能性,此构造函数的用户必须确保p至少在所有权组r被销毁之前保持有效. - 结束说明.]

[注意:此构造函数允许 使用非NULL存储指针创建 shared_ptr实例. - 结束说明.]