Should I use a smart pointer?

故事扮演 提交于 2019-11-30 20:35:57
Puppy

Always use a smart pointer wherever you own resources (memory, files etc). Owning them manually is extremely error prone and violates many good practices, like DRY.

Which one to use depends on what ownership semantics you need. unique_ptr is best for single ownership, and shared_ptr shared ownership.

As children do not own their parents, a raw parent pointer is fine. However, if the parents own their children, unique_ptr works best here.

It's also notable that what on earth, a linked list of pointers? That makes no sense. Why not a linked list of values?

It is always a good idea to use smart pointers, but beware of loops of references.

class node
{
public:
     std::weak_ptr<node> parent;
     std::list< std::shared_ptr<node> > children;
};

That's why there is the weak_ptr in the first place. Note that they are not so smart to detect the loops, you have to do it manually, and break them by using weak_ptrs.

Absolutely not. The usual smart pointers don't work with graph-like structures, and should be avoided. In this case, you have a tree, and there's no problem handling all of the deletions (and allocations) from the tree object itself.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!