Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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?

like image 876
AtheS21 Avatar asked Jul 27 '17 03:07

AtheS21


People also ask

What does pointer & 1 mean?

Another way of seeing it: by doing i+1 you actually increment the pointer to point to next int -which means incrementing the pointer address by 4 as you said-. This is automatically done by the compiler.

What is this pointer in C?

A pointer is a variable that stores the memory address of another variable as its value. A pointer variable points to a data type (like int ) of the same type, and is created with the * operator.

What does * represent in pointers?

The asterisk * used to declare a pointer is the same asterisk used for multiplication. However, in this statement the asterisk is being used to designate a variable as a pointer.


3 Answers

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

like image 80
Jonathan Olson Avatar answered Sep 21 '22 20:09

Jonathan Olson


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.

like image 33
Tas Avatar answered Sep 21 '22 20:09

Tas


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.

like image 21
Thomas G. Avatar answered Sep 21 '22 20:09

Thomas G.