Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where memory for 'this' pointer allocated

Tags:

c++

pointers

this

In C++, this pointer get passed to method as a hidden argument which actually points to current object, but where 'this' pointer stored in memory... in stack, heap, data where?

like image 224
nilesh Avatar asked Jan 12 '14 03:01

nilesh


1 Answers

The standard doesn't specify where the this pointer is stored.

When it's passed to a member function in a call of that function, some compilers pass it in a register, and others pass it on the stack. It can also depend on the compiler options.

About the only thing you can be sure of is that this is an rvalue of basic type, so you can't take its address.

It wasn't always that way.

In pre-standard C++ you could assign to this, e.g. in order to indicate constructor failure. This was before exceptions were introduced. The modern standard way of indicating construction failure is to throw an exception, which guarantees an orderly cleanup (if not foiled by the user's code, such as the infamous MFC placement new bug).

like image 197
Cheers and hth. - Alf Avatar answered Oct 03 '22 16:10

Cheers and hth. - Alf