C++: Replace raw pointers with shared and weak ptr

前端 未结 4 669
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 16:17

I\'m facing a design issue in my program. I have to manage Nodes object which are part of a root ChainDescriptor.

Basically it looks like the following:



        
4条回答
  •  甜味超标
    2021-01-13 16:48

    You can use shared_ptr for m_childs and weak_ptr for m_parent.

    However, it might be still reasonable to retain the raw pointer to the parent Node and don't use any weak pointers at all. The safeguarding mechanism behind this is the invariant that non-null parent always exists.

    Another option is using shared_ptr in ChainDescriptor only and retaining all raw pointers in Node. This approach avoids weak pointers and has a clean ownership policy (parent nodes own their children).

    Weak pointers will help you to manage the memory automatically, but the backside of this are fuzzy ownership logic and performance penalties.

提交回复
热议问题