【问题标题】:How to reassign a boost shared_ptr如何重新分配提升 shared_ptr
【发布时间】:2012-04-10 17:32:08
【问题描述】:

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

【问题讨论】:

  • 你试过了吗?有什么不工作吗?看起来不错。
  • 如果您只是在寻找确认,是的,C = B; 是正确的。
  • 是的,这行得通,为什么不试试呢??
  • C.reset(new X);C = A 如果 Ashared_ptr&lt;X&gt;

标签: c++ boost shared-ptr


【解决方案1】:

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/

希望对您有所帮助, 欢迎询问更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多