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

2019-03-11 14:44发布

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?

标签: c++
4条回答
对你真心纯属浪费
2楼-- · 2019-03-11 14:48

this is simply a pointer which refers to this object. Since it's a pointer, you can apply pointer arithmetic and even array indexing.

If this object is an element in an array, this+1 would point to the next object in the array.

If it's not, well it's just going to treat whatever is at that memory the same as this object, which will be undefined behaviour unless it is the same type.

查看更多
成全新的幸福
3楼-- · 2019-03-11 14:53

As it is NLP it makes sense to optimize memory management. I assume you find overloaded new/delete methods as well.

The this+1 construct assumes all objects reside in an array. The name 'childrenEnd' of the method indicates it returns a pointer to an address of the end of the children of the current node.

Thus you are looking at an implementation of a tree structure. All siblings are adjacent and their children as well.

查看更多
Viruses.
4楼-- · 2019-03-11 14:55

Presumably this is part of an array, so this+1 would refer to the next object in that array.

查看更多
相关推荐>>
5楼-- · 2019-03-11 15:01

"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.

查看更多
登录 后发表回答