Is it bad practice for a child object to have a pointer to its parent?

前端 未结 7 1747
我寻月下人不归
我寻月下人不归 2020-12-20 12:27

In a C++ application, let\'s say I have a window class, which has several instances of a control class. If my window wanted to notify a control that it had been clicked, I m

7条回答
  •  既然无缘
    2020-12-20 13:08

    You can consider a hierarchy of controls as being a tree-like graph data structure; when you visualize it that way, it's quite reasonable for a control to have a pointer to its parent.

    As for whether objects or pointers to objects should be stored in a vector, well, it depends. You should usually prefer to store objects, but there are a lot of times that you can't do so or it's impractical to do so. For example, if you need to take advantage of polymorphism and store different types of things all derived from a common base class, you'll need to use pointers.

    If you do store pointers, make sure to either use a smart pointer of some kind or a pointer container; otherwise, exception safety is a beating.

提交回复
热议问题