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

前端 未结 5 550
旧巷少年郎
旧巷少年郎 2021-02-03 18:51

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


        
5条回答
  •  南方客
    南方客 (楼主)
    2021-02-03 19:17

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

提交回复
热议问题