std::shared_ptr of this

前端 未结 2 1947
有刺的猬
有刺的猬 2020-11-28 21:34

I am currently trying to learn how to use smart pointers. However while doing some experiments I discovered the following situation for which I could not find a satifying so

2条回答
  •  时光说笑
    2020-11-28 21:37

    You have several problems in you design, that seem to stem from you misunderstanding of smart pointers.

    Smart pointers are used to declare ownership. You are breaking this by declaring that both the parents owns all children, but also that each child own it's parent. Both can't be true.

    Also, you are returning a weak pointer in getChild(). By doing so, you are declaring that the caller shouldn't care about the ownership. Now this can be very limiting, but also by doing so, you must make sure that the child in question won't get destroyed while any weak pointers are still held, if you would use a smart pointer, it would get sorted out by itself.

    And the final thing. Usually, when you are accepting new entities, you should usually accept raw pointers. Smart pointer can have their own meaning for swapping children between parents, but for general usage, you should accept raw pointers.

提交回复
热议问题