Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

this[0] is the same as *(this + 0), so indeed this is fine (albeit a bit weird).

Yep, it's the same thing as *this

AFAIK basically this[0] is exactly the same as *this, as this is just a normal pointer. So yes it is safe to use.

array[1] would be the same as *(array + 1) (when array is valid) fyi...

It is equivalent (by definition) to *(this + 0), which is the same as *this. It is safe and well-defined, but weird.

this[0] is same as *(this + sizeof(this)*0) so it's quite safe

Added small test as answer to comment

struct A
{
    void * _a;
    int _b;

    A * getThis(int index)
    {
        return &(this[index]);
    }
};

int main(int argc, char * argv[])
{
    A mas[100];

    std::cout << ((long long) mas[0].getThis(50) == (long long) &(mas[50])) << std::endl;
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top