如何将 "this" 指针分配给字段?
How is it possible to assign "this" pointer to field?
据我所知,"this" 指针是编译器插入到函数中的参数,如下所示:
class Sample {
private:
int a;
public:
void setA(int a) {
this->a = a;
}
};
Sample ob;
ob.setA(5); -> ob.setA(&ob, 5);
class Sample {
private:
int a;
public:
void setA(Sample* this, int a) {
this->a = a;
}
};
顺便说一句,我发现一些令人困惑的代码将 "this" 指针分配给 const 字段。 (参考下方)
class Test {
int data;
public:
Test* const test = this;
Test(int data = 1) : data(data) { }
Test(Test &test) : data(test.data) { }
};
(It has no compile Errors and runs well!)
如果 "this" 指针是通过函数传递的,那怎么可能呢?
我不知道..
你能给我一些建议吗?感谢您的任何回复。
class(在本例中为 Test.test
)的属性由编译器生成的代码隐式初始化。有一个函数,它确实接收 this
指针,但它都是由编译器生成的,这就是为什么你看不到它的原因。
此语法:
Test* const test = this;
来自 C++11。意思是"initialize test
to this
inside any non-copy constructor which does not already initialize test
explicitly".
因此,这段代码是在构造函数内部执行的,this
完全有效。但是,进行这种初始化的好处尚不清楚,依赖于 test
的用法可能很危险。
据我所知,"this" 指针是编译器插入到函数中的参数,如下所示:
class Sample {
private:
int a;
public:
void setA(int a) {
this->a = a;
}
};
Sample ob;
ob.setA(5); -> ob.setA(&ob, 5);
class Sample {
private:
int a;
public:
void setA(Sample* this, int a) {
this->a = a;
}
};
顺便说一句,我发现一些令人困惑的代码将 "this" 指针分配给 const 字段。 (参考下方)
class Test {
int data;
public:
Test* const test = this;
Test(int data = 1) : data(data) { }
Test(Test &test) : data(test.data) { }
};
(It has no compile Errors and runs well!)
如果 "this" 指针是通过函数传递的,那怎么可能呢? 我不知道.. 你能给我一些建议吗?感谢您的任何回复。
class(在本例中为 Test.test
)的属性由编译器生成的代码隐式初始化。有一个函数,它确实接收 this
指针,但它都是由编译器生成的,这就是为什么你看不到它的原因。
此语法:
Test* const test = this;
来自 C++11。意思是"initialize test
to this
inside any non-copy constructor which does not already initialize test
explicitly".
因此,这段代码是在构造函数内部执行的,this
完全有效。但是,进行这种初始化的好处尚不清楚,依赖于 test
的用法可能很危险。