使用“这个”是安全的。指针在初始化列表中? [英] Is it safe to use the "this" pointer in an initialization list?

查看:139
本文介绍了使用“这个”是安全的。指针在初始化列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个具有父子关系的类( Parent classhas-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
{
public:
 Child (Parent* parnet_ptr_) : parent_ptr(parent_ptr_) {};

private:
 Parent* parent_ptr;
};

class Parent
{
public:
    Parent() : child(this) {};

private:
    Child child;
}



现在,我知道人们建议不要使用 / code>在初始化列表中,并且 C ++常见问题表示,我得到一个编译器警告(BTW,在VS2010,我没有得到警告),但我真的很喜欢这个更好,然后调用 Parent 的构造函数中的一些set函数。我的问题是:

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:


  • 是 c

  • 如果是,为什么被认为是不好的做法,如上所述?

  • 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?

谢谢,

Boaz

编辑:感谢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;
}


推荐答案

在初始化列表中使用指针是安全的,只要它不会直接或间接地用于访问未初始化的成员或虚拟函数该对象尚未完全构建。对象 child 可以存储指针后来使用!

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!

这篇关于使用“这个”是安全的。指针在初始化列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆