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

前端 未结 5 548
旧巷少年郎
旧巷少年郎 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 18:55

    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.

    0 讨论(0)
  • 2021-02-03 19:01

    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.

    0 讨论(0)
  • 2021-02-03 19:14

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

    0 讨论(0)
  • 2021-02-03 19:17

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题