4

我有两个 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;
4

1 回答 1

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/

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

于 2013-07-08T20:34:03.733 回答