“this”指针存储在计算机内存中? [英] Where is the 'this' pointer stored in computer memory?
问题描述
this指针存储在内存中的什么位置?是分配在堆栈,堆还是数据段?
Where exactly is the 'this' pointer stored in memory? Is it allocated on the stack, in the heap, or in the data segment?
#include <iostream>
using namespace std;
class ClassA
{
int a, b;
public:
void add()
{
a = 10;
b = 20;
cout << a << b << endl;
}
};
int main()
{
ClassA obj;
obj.add();
return 0;
}
在上面的代码中我调用成员函数 add()
,接收器对象作为this指针隐式传递。
In the above code I am calling the member function add()
and the receiver object is passed implicitly as the 'this' pointer. Where is this
stored in memory?
推荐答案
其他答案非常好的工作,解释了典型的编译器如何实现 this
(通过将其作为隐式的第一个参数传递给函数)。
Other answers have done a very good job explaining how a typical compiler implements this
(by passing it as an implicit first parameter to the function).
我认为看看什么是C ++ ISO规范明确说明这一点也很有用。根据C ++ 03 ISO规范,9.3.2 / 1:
I think it's also useful to see what the C++ ISO spec explicitly says about this. According to the C++03 ISO spec, §9.3.2/1:
在非静态函数,关键字
这个
是一个非值的表达式,其值是调用函数的对象的地址。
In the body of a nonstatic (9.3) member function, the keyword
this
is a non-lvalue expression whose value is the address of the object for which the function is called.
重要的是要注意这个
是不一个变量 - 它是一个 / em>,与表达式 1 + 2 * 3
大致相同。这个表达式的值允许存储在任何地方。编译器可能将它放在堆栈上,并将其作为隐式参数传递给函数,或者可能将其放入寄存器,并且可以将其置于堆或在数据段中。
It's important to note that this
is not a variable - it's an expression, much in the same way that the expression 1 + 2 * 3
is an expression. The value of this expression is permitted to be stored pretty much anywhere. The compiler might put it on the stack and pass it as an implicit parameter to a function, or it might put it in a register, and it conceivably could put it in the heap or in the data segment. The C++ specification deliberately gives the implementation some flexibility here.
我认为语言律师的答案是这是完全实现定义的,此外 this
在技术上不是一个指针,而是一个计算为指针的表达式。
I think that the "language-lawyer" answer is "this is completely implementation-defined, and moreover this
is technically not a pointer, but an expression that evaluates to a pointer."
希望这有助于!
这篇关于“this”指针存储在计算机内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!