使用“this"是否安全?初始化列表中的指针?
我有两个具有父子关系的类(Parent
类has-a"Child
类)和 Child
类有一个返回 Parent
的指针.在构造孩子时初始化父指针会很好,如下所示:
I have two classes with a parent-child relationship (the Parent
class "has-a" Child
class), and the Child
class has a pointer back to the Parent
. It would be nice to initialize the parent pointer upon construction of the child, as follows:
class Child;
class Parent;
class Child
{
public:
Child (Parent* parent_ptr_) : parent_ptr(parent_ptr_) {};
private:
Parent* parent_ptr;
};
class Parent
{
public:
Parent() : child(this) {};
private:
Child child;
}
现在,我知道人们建议不要在初始化列表中使用 this
和 C++ FAQ 说我会收到编译器警告(顺便说一句,在 VS2010 上,我没有收到警告),但我真的更喜欢这个,然后调用一些 set 函数在 Parent
的构造函数中.我的问题是:
Now, I know people recommend not using this
in initialization list, and C++ FAQ says I'm gonna get a compiler warning (BTW, on VS2010, I don't get a warning), but I really like this better then calling some set function in Parent
's constructor. My questions are:
- 在创建
Child
对象时,父this
指针是否明确定义? - 如果是这样,为什么按上述方式使用它被认为是不好的做法?
- Is the parent
this
pointer well-defined when theChild
object is being created? - If so, why is it considered bad practice to use it as above?
谢谢,
博阿斯
感谢 Timbo,它确实是一个 重复(呵呵,我什至选择了相同的类名).所以让我们获得一些附加值:参考怎么样?是否可以/安全地执行以下操作?:
Thanks Timbo, it is indeed a duplicate (huh, I even chose the same class names). So lets get some added value: how about references? Is it possible / safe to do the following? :
class Child
{
public:
Child (Parent& parnet_ptr_) : parent_ptr(parent_ptr_) {};
private:
Parent* parent_ptr;
};
class Parent
{
public:
Parent() : child(*this) {};
private:
Child child;
}
推荐答案
是的.在初始化列表中使用 this
指针是安全的只要它不用于直接或间接访问未初始化的成员或虚函数,因为对象尚未完全建造.child
对象可以存储 Parent
的 this
指针以备后用!
Yes. It's safe to use this
pointer in initialization-list as long as it's not being used to access uninitialized members or virtual functions, directly or indirectly, as the object is not yet fully constructed. The object child
can store the this
pointer of Parent
for later use!
相关文章