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

前端 未结 5 558
旧巷少年郎
旧巷少年郎 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: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.

提交回复
热议问题