Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is this size computed?

Tags:

c++

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)?

like image 705
uh oh somebody needs a pupper Avatar asked Jan 07 '23 01:01

uh oh somebody needs a pupper


1 Answers

Is this-> considered a no-op in this case and it's essentially equivalent to sizeof(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.

like image 177
Lightness Races in Orbit Avatar answered Jan 15 '23 22:01

Lightness Races in Orbit