C++ 共享boost的所有权::构建后共享的ptr

C++ 共享boost的所有权::构建后共享的ptr,c++,boost,shared-ptr,C++,Boost,Shared Ptr,假设我有两个boost::shared_ptr指向类A的两个不同对象: boost::shared_ptr<A> x = boost::make_shared<A>(); boost::shared_ptr<A> y = boost::make_shared<A>(); boost::shared_ptr x=boost::make_shared(); boost::shared_ptr y=boost::make_shared(); 在某个时

假设我有两个
boost::shared_ptr
指向
类A
的两个不同对象:

boost::shared_ptr<A> x = boost::make_shared<A>();
boost::shared_ptr<A> y = boost::make_shared<A>();
boost::shared_ptr x=boost::make_shared();
boost::shared_ptr y=boost::make_shared();
在某个时刻,我需要
x
放弃它所拥有的对象的所有权,并与
y
共享
y
对象的所有权。如何实现这一点(请注意,两个共享的_ptr都是在该点上构造的,因此没有机会使用复制构造函数)


谢谢

您可以简单地分配它:

x = y;
请参阅和。您可以通过检查分配前后的引用计数来验证这一点。本例使用C++11的
std::shared_ptr
,但
boost::shared_ptr
将产生相同的结果:

#include <memory>
int main()
{
    std::shared_ptr<int> x(new int);
    std::cout << x.use_count() << "\n"; // 1
    std::shared_ptr<int> y(new int);
    std::cout << x.use_count() << "\n"; // still 1
    y = x;
    std::cout << x.use_count() << "\n"; // 2
}
#包括
int main()
{
标准::共享_ptr x(新整数);

std::cout您可以简单地分配它:

x = y;
请参阅和。您可以通过检查赋值前后的引用计数来验证这一点。此示例使用C++11的
std::shared_ptr
,但
boost::shared_ptr
将产生相同的结果:

#include <memory>
int main()
{
    std::shared_ptr<int> x(new int);
    std::cout << x.use_count() << "\n"; // 1
    std::shared_ptr<int> y(new int);
    std::cout << x.use_count() << "\n"; // still 1
    y = x;
    std::cout << x.use_count() << "\n"; // 2
}
#包括
int main()
{
标准::共享_ptr x(新整数);

std::cout根据文档,分配操作员交换(即不共享)所有权,对吗?@HaithamGad它共享RHS指针的所有权,因此
x
放弃它构建时使用的指针的所有权,并共享
y
管理的指针的所有权。根据文档,赋值运算符交换(即不共享)所有权,对吗?@HaithamGad它共享RHS指针的所有权,因此
x
放弃它构造时使用的指针的所有权,并共享由
y
管理的指针的所有权。