我什么时候应该使用weak_ptr?

时间:2013-07-30 03:44:53

标签: c++ smart-pointers weak-references weak-ptr

我知道weak_ptr是避免循环引用的好方法。

但是我不确定是否应该在可能的情况下使用它来提高性能,例如在读取指针中的内容时。

E.g。我有一个存储智能指针的向量:

typedef shared_ptr<MyClass> MyClassPtr;
vector<MyClassPtr> v;
v.push_back(..);
...

我有一个搜索项目并将其打印出来的功能。

void foo(vector<MyClassPtr> &v) {
  // find and get an item at i
  MyClassPtr ptr = v[i]; // <-- Do I really need to increase reference count here? 
                         //     I just want to print out the item's content.
  ptr->print();
}

在这种情况下使用weak_ptr会更好吗?我应该注意哪些陷阱?

0 个答案:

没有答案
相关问题