Is it safe to use the quot;thisquot; pointer in an initialization list?(使用“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
thispointer well-defined when theChildobject 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!
这篇关于使用“this"是否安全?初始化列表中的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用“this"是否安全?初始化列表中的指针?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
