What is the 'this' pointer?

2019-01-06 15:07发布

I'm fairly new to C++, and I don't understand what the this pointer does in the following scenario:

void do_something_to_a_foo(Foo *foo_instance);


void Foo::DoSomething()
{
  do_something_to_a_foo(this);
}

I grabbed that from someone else's post on here.

What does this point to? I'm confused. The function has no input, so what is this doing?

8条回答
Fickle 薄情
2楼-- · 2019-01-06 15:47

Nonstatic member functions such as Foo::DoSomething have an implicit parameter whose value is used for this. The standard specifies this in C++11 §5.2.2/4:

When a function is called, each parameter (8.3.5) shall be initialized (8.5, 12.8, 12.1) with its corresponding argument. [Note: Such initializations are indeterminately sequenced with respect to each other (1.9) — end note ] If the function is a non-static member function, the this parameter of the function (9.3.2) shall be initialized with a pointer to the object of the call, converted as if by an explicit type conversion (5.4).

As a result, you need a Foo object to call DoSomething. That object simply becomes this.

The only difference (and it's trivial) between the this keyword and a normal, explicitly-declared const pointer parameter is that you cannot take the address of this.

查看更多
手持菜刀,她持情操
3楼-- · 2019-01-06 15:47

It is a local pointer.It refers to the current object as local object

查看更多
登录 后发表回答