如何重新分配boost shared_ptr

时间:2012-04-10 17:32:08

标签: c++ boost shared-ptr

我有两个Boost shared_ptr的

shared_ptr<X> A(new X);
shared_ptr<X> B(new X);

第三个指针最初指向与A相同的X.

shared_ptr<X> C = A;

更改C的正确方法是什么,它指向与B相同的X?

C = B;

1 个答案:

答案 0 :(得分:2)

EdChm是对的。我做了一个小测试程序来明确它。 它使用C ++ 11,但可以轻松转换。

#include <iostream>
#include <memory>

int main()
{
  std::shared_ptr<int> A(new int(1));//creates a shared pointer pointing to an int. So he underlying int is referenced only once
  std::shared_ptr<int> B(new int(2));//creates another shared pointer pointing to another int (nothing to do with the first one so the underlying int is only referenced once
  std::shared_ptr<int> C;//creating a shared pointer pointing to nothing

  std::cout<<"Number of references for A "<< A.use_count()<<std::endl;
  std::cout<<"A points to "<<*(A.get())<<std::endl;
  std::cout<<"Number of references for B "<< B.use_count()<<std::endl;
  std::cout<<"A points to "<<*(B.get())<<std::endl;
  std::cout<<"Number of references for C "<< C.use_count()<<std::endl;

  std::cout<<"Now we assign A to C"<<std::endl;
  C=A; // now two shared_ptr point to the same object
  std::cout<<"Number of references for A "<< A.use_count()<<std::endl;
  std::cout<<"A points to "<<*(A.get())<<std::endl;
  std::cout<<"Number of references for C "<< C.use_count()<<std::endl;
  std::cout<<"C points to "<<*(C.get())<<std::endl;

  std::cout<<"Number of references for B "<< B.use_count()<<std::endl;
  std::cout<<"B points to "<<*(B.get())<<std::endl;
  return 0;
}

这个例子很大程度上受到了这个链接的启发。 http://www.cplusplus.com/reference/memory/shared_ptr/shared_ptr/

希望有所帮助, 请随时询问更多详细信息。