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

前端 未结 4 643
伪装坚强ぢ
伪装坚强ぢ 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

    Trying to just replace raw pointers with some sort of smart pointer will in general not work. Smart pointers have different semantics than weak pointers, and usually, these special semantics need to be taken into account at a higher level. The "cleanest" solution here is to add support for copy in ChainDescriptor, implementing a deep copy. (I'm supposing here that you can clone Node, and that all of the Node are always owned by a ChainDescriptor.) Also, for undo, you may need a deep copy anyway; you don't want modifications in the active instance to modify the data saved for an undo.

    Having said that, your nodes seem to be used to form a tree. In this case, std::shared_ptr will work, as long as 1) all Node are always "owned" by either a ChainDescriptor or a parent Node, and 2) the structure really is a forest, or at least a collection of DAG (and, of course, you aren't making changes in any of the saved instances). If the structure is such that cycles may occur, then you cannot use shared_ptr at this level. You might be able to abstract the list of nodes and the trees into a separate implementation class, and have ChainDescriptor keep a shared_ptr to this.

    (FWIW: I used a reference counted pointer for the nodes in a parse tree I wrote many years ago, and different instances could share sub-trees. But I designed it from the start to use reference counted pointers. And because of how the tree was constructed, I was guaranteed that there could be no cycles.)

提交回复
热议问题