This earlier question asks what this[0]
means in C#. In C++, this[0]
means "the zeroth element of the array pointed at by this
."
Is it guaranteed to not cause undefined behavior in C++ to refer to the receiver object this way? I'm not advocating for using this syntax, and am mostly curious whether the spec guarantees this will always work.
Thanks!
For any valid object pointer p
, p[0]
is equivalent to *p
. So this[0]
is equivalent to *this
. There's nothing more to it. Just like you can dereference any valid pointer using [0]
, you can dereference this
with it.
In other words, it is just a "tricky" way to write *this
. It can be used to obfuscate code. It can probably be used in some specific circumstances for useful purposes as well, since any standalone object can be thought of as an array of size 1. (From C++03, Additive operators: "For the purposes of these operators, a pointer to a nonarray object behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type.")
P.S. As Johannes noted in the comments, by using C++11 features it is possible to come up with a context in which this
is a pointer to an incomplete type. In that case this[0]
expression becomes invalid, while *this
expression remains valid.