[C++] Smart Pointers 問題

本帖最後由 luckiejacky 於 2015-7-10 20:49 編輯

為什麼 cyclic dependency with Smart pointers will always lead to memory leak?
  1. std::vector<boost::shared_ptr<AABB>> vAABBs;
  2. boost::shared_ptr<AABB> a;
  3. //...
  4. vAABBs.push_back(a);

  5. a->setNeighbours(vAABBs);

  6. class AABB
  7. {
  8. //...//
  9. public:
  10.      void setNeighbours(std::vector<boost::shared_ptr<AABB>> neighbours);
  11. private:
  12.     std::vector<boost::shared_ptr<AABB>> neighbours;
  13. };
I have a few cases that this setup will lead to memory leaks where raw pointers won't
How come?

因為smart pointer建基於reference counting
smart pointer對object keep一份record,記低有幾多個shared_ptr point to that object (reference count)
然後每當一個指住果個object既shared pointer destruct,就將個reference count減一
當reference count = 0就destruct果個object

cyclic reference既問題係,兩個object各自hold住指向對方既shared pointer
於是雙方既reference count都keep住係1,雙方都要等到對方destruct時先destruct

解決方法:search "weak pointer"

via HKEPC Reader for Android


本帖最後由 luckiejacky 於 2015-7-10 12:50 編輯

Ok, this way the object won't be destructed...


回覆 2# FlyingForever

    正解. 而家啲library有好多種smart pointer用, 每種都設計成有特定用途.