What does the pointer 'this+1' refer to in C++?

Viewed 6761

I was wandering through the code of Sequitur G2P and found a really strange line of code:

public:
    ...
    const Node *childrenEnd() const { return (this+1)->finalized.firstChild_; }

I know that this is a pointer to the current object, and since it is a pointer, the operation is perfectly legal, but what does this+1 actually refer to?

5 Answers

"this + 1" in C++ class means:

if the "this" object is a member of another object it will point to the address of the parent's object next variable declared just after the "this" object variable:

Example:

class B
{
public:
    void* data()
    {
        return this + 1;
    }
};

class A
{
public:
    B m_b;
    char m_test;
};

int main(int argc, char* argv[])
{
    A a;
    a.m_test = 'H';

    void* p = a.m_b.data();
    char c;

    memcpy(&c, p, sizeof(char));
    return 0;
}

c is equal 'H'.

Long story short it allows to access to parent's class data without passing parent's pointer to the child class. In this example this + 1 point to the m_test member of the class A.

Actually, there is a case, when this thing could be used. I don't recommend to use this method, but it certainly works.

I believe, in NLP code it was used something like that:

when you want your object to behave as a collection (an array etc) to use it similarly as an array with something range-based etc, you can do this trick:

struct Obj {
...
Obj* begin() { return this; }
Obj* end() { return this+1; }
...
}

Now, you can use this object in, for example, range-based for-loops... Sometimes all that is necessary... but just even there you'd better use "nullptr" or even do refactoring than to use this trick.

Related