传递“这个”从一个构造函数内的函数? [英] Passing "this" to a function from within a constructor?

查看:102
本文介绍了传递“这个”从一个构造函数内的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以从类构造函数中将this作为指针传递给函数,并在构造函数返回之前使用它指向对象的成员?

Can I pass "this" to a function as a pointer, from within the class constructor, and use it to point at the object's members before the constructor returns?

是否可以安全地执行此操作,只要访问的成员在函数调用之前正确初始化?

Is it safe to do this, so long as the accessed members are properly initialized before the function call?

例如:

#include <iostream>

class Stuff
{
public:
    static void print_number(void *param)
    {
    	std::cout << reinterpret_cast<Stuff*>(param)->number;
    }

    int number;

    Stuff(int number_)
    	: number(number_)
    {
    	print_number(this);
    }
};

void main() {
    Stuff stuff(12345);
}

我以为这不会工作,但似乎。

I thought this wouldn't work, but it seems to. Is this standard behavior, or just undefined behavior going my way?

推荐答案

在C ++中实例化一个对象时,构造函数是最后执行的。所有其他初始化,包括超类初始化,超类构造函数执行和内存分配预先发生。构造函数中的代码实际上只是在构建对象时执行额外的初始化。因此,在类构造函数中使用this指针并假设它指向一个完全构造的对象是完全有效的。

When you instantiate an object in C++, the code in the constructor is the last thing executed. All other initialization, including superclass initialization, superclass constructor execution, and memory allocation happens beforehand. The code in the constructor is really just to perform additional initialization once the object is constructed. So it is perfectly valid to use a "this" pointer in a class' constructor and assume that it points to a completely constructed object.

当然,你仍然需要注意未初始化的成员变量,如果你还没有在你的构造函数代码中初始化它们。

Of course, you still need to beware of uninitialized member variables, if you haven't already initialized them in your constructor code.

这篇关于传递“这个”从一个构造函数内的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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