1

I know that weak_ptr is a good way to avoid cyclic references.

However I'm not sure whether I should use it to improve performance when possible, for example when just reading the content in the pointer.

E.g. I have a vector storing smart pointers:

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

And I have a function to search an item and print it out.

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();
}

Is it better if using weak_ptr in this case? Is there any pitfalls I should be aware of?

Deqing
  • 11,990
  • 13
  • 74
  • 113

0 Answers0