As mentioned in the title, I would like to know about the type of 'this'
pointer.
I'm working on a project and I observed that the type of 'this'
pointer is "ClassName * const this"
on windows using VC++ 2008. Well I would want to know what is the need/requirement to make the this pointer a constant pointer. Thanks.
Best Answer
The type of this pointer is either
ClassName *
orconst ClassName *
, depending on whether it is inspected inside a non-const or const method of the classClassName
. Pointerthis
is not an lvalue.The observation you mentioned above is misleading. Pointer
this
is not an lvalue, which means that it cannot possibly haveClassName * const
type, i.e. it cannot possible have aconst
to the right of the*
. Non-lvalues of pointer type cannot be const or non-const. There's simply no such concept in C++ language. What you observed must be an internal quirk of the specific compiler. Formally, it is incorrect.Here are the relevant quotes from the language specification (emphasis mine)
It is worth nothing that back in the C++98/C++03 times several compilers used an internal implementational trick: they interpreted their
this
pointers as constant pointers, e.g.ClassName *const
in a non-constant method of classClassName
. This apparently helped them to ensure non-modifiablity ofthis
. GCC and MSVC are known to have used the technique. It was a harmless trick, since at language levelthis
was not an lvalue and its constness was undetectable. That extraconst
would generally reveal itself only in diagnostic messages issued by the compiler.However, with the advent of rvalue references in C++11 it became possible to detect this extra
const
on the type ofthis
. For example, the following code is valid in C++11Yet it will typically fail to compile in implementations that still use the aforementioned trick. GCC has since abandoned the technique. MSVC++ still uses it (as of VS2017), which prevents the above perfectly valid code from compiling in MSVC++.