[英]Is it bad practice to have a child object have a reference to its parent object instead of a pointer?
Related to this , I would like to know if there are reasons to use pointers to a parent object (not talking about a parent class) instead of references. 与此相关,我想知道是否有理由使用指向父对象的指针(而不是父类)而不是引用。
Obviously, if the parent could be null, a reference will not work. 显然,如果父级可以为null,则引用将不起作用。 But what if the parent object creates and destroys the child object in its lifetime so that the child object's pointer back to its parent will never be null? 但是,如果父对象在其生命周期中创建并销毁了子对象,以使子对象指向其父对象的指针永远不会为空,该怎么办? I think it sounds okay in this case, but I have not seen others do it and am still learning a lot about C++. 在这种情况下,我认为这还可以,但是我还没有看到其他人这样做,并且仍在学习有关C ++的很多知识。
The specific case I am thinking of is a specialized dialog window that will only be created by a certain window class. 我正在考虑的特定情况是专门的对话框窗口,它将仅由特定的窗口类创建。
What are some problems (if any) with doing 这样做有什么问题(如果有)
class Child {
Child(Parent& parent) : parent_(parent) {}
Parent& parent_;
};
versus 与
class Child {
Child(Parent* parent) : parent_(parent) {}
Parent* parent_;
};
People will argue about it all day long but references are just limited pointers. 人们会整日争论这个问题,但是引用只是有限的指针。 Don't agonize about which to use. 不要为使用哪个而烦恼。
The advantage of a pointer is you can copy childs, or create a child without a parent, to be given one later. 指针的优点是您可以复制子项,或创建一个没有父项的子项,以供以后使用。 If you need to do this, you have to use a pointer. 如果需要执行此操作,则必须使用指针。
If not, use whichever makes you feel warmest inside. 如果没有,请使用使您感觉最温暖的任何一种。 It just isn't worth worrying about. 只是不值得担心。
If you make the pointer Parent *const parent_
it is effectively the same as a reference. 如果将指针Parent *const parent_
,则它实际上与引用相同。
here are some differences between references and pointers : 这是引用和指针之间的一些区别:
References : 参考文献:
Pointers : 指针:
Consequences : 后果:
Thus depending on the relationship you want to have between child and parents, you will choose pointer or reference. 因此,根据您希望在孩子与父母之间建立的关系,您将选择指针或参考。 Also prefer reference to pointer if you dont need pointer. 如果不需要指针,也希望引用指针。
In other words, if child object have the same parent during its lifetime and parent exists at the creation of the child : use reference to point to parent. 换句话说,如果子对象在其生命周期中具有相同的父对象,并且在创建子对象时存在父对象:请使用引用指向父对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.