5.1.1/2 is stated that:
The keyword
this
names a pointer to the object for which a non-static member function (9.3.2) is invoked or a non-static data member’s initializer (9.2) is evaluated.
And:
Unlike the object expression in other contexts,
*this
is not required to be of complete type for purposes of class member access (5.2.5) outside the member function body.
The following code prints 8
:
#include <cstddef>
#include <iostream>
struct Test
{
std::size_t sz = sizeof(this->sz);
};
int main()
{
std::cout << Test{}.sz;
}
5.3.3 says:
The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id. The
sizeof
operator shall not be applied to an expression that has function or incomplete type...
sizeof this->sz
has the same result.
Is this->
considered a no-op in this case and it's essentially equivalent to sizeof(sz)
?
Is
this->
considered a no-op in this case and it's essentially equivalent tosizeof(sz)
?
That's right.
The type of this->sz
is std::size_t
, a complete type in that context.
The type of *this
is not complete here, but you quoted the passage stating why that doesn't matter and we can go straight through to analysing sz
specifically.
As such, the this->
had no actual effect on the semantics of the expression, either for better or for worse.
As Sergey said, there is one case where using this->
for member access makes a difference (template bases!), and this is not one of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With