使用“this"是否安全?初始化列表中的指针?

Is it safe to use the quot;thisquot; pointer in an initialization list?(使用“this是否安全?初始化列表中的指针?)

本文介绍了使用“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 the Child 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 对象可以存储 Parentthis 指针以备后用!

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"是否安全?初始化列表中的指针?

基础教程推荐