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;

最佳答案 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/

希望有所帮助,
随意询问更多细节.

点赞