I have code very similiar to this:
LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator+(const Iterator& right)const
{
return (this + &am
742 Evergreen Terrace + 1 = 743 Evergreen Terrace
742 Evergreen Terrace - 1 = 741 Evergreen Terrace
743 Evergreen Terrace - 741 Evergreen Terrace = 2
743 Evergreen Terrace + 741 Evergreen Terrace = ???
I suppose in your example the result you were expecting was to add or subtract a pointer to an offset to be moved, not to another pointer.
In C++ you can subtract 2 pointers (getting the offset in memory between them) or add a pointer to an integer value (moving a pointer to another memory location being incremented by value * sizeof(object_class)). Just adding 2 pointers do not make sense in C++, but if you are sure you want to add 2 memory locations adresses, just add then as unsigned integer values (using typecast).
Why I'm getting an err in one place and not in both?
Even if you were allowed to add two pointers, this:
return (this + &right);
would point to nowhere. Think about it - this might be something like 0x00123456, and &right will be somewhere in the same range (0x00000000..0x80000000 - i.e. 0x00321321, for example). If you add them up, the resulting address will point very far away from both variables (0x00123456 + 0x00321321 == 0x00444777, which will be way too far from both "this" and &right), you might get into reserved memory (0x8xxxxxxx on win), etc. Also, pointers could overflow. Which is (probably) why it is forbidden.
If you want to add something to pointer, add integer.
Pointer addition is forbidden in C++, you can only subtract two pointers.
The reason for this is that subtracting two pointers gives a logically explainable result - the offset in memory between two pointers. Similarly, you can subtract or add an integral number to/from a pointer, which means "move the pointer up or down". Adding a pointer to a pointer is something which is hard to explain. What would the resulting pointner represent?
If by any chance you explicitly need a pointer to a place in memory whose address is the sum of some other two addresses, you can cast the two pointers to int
, add int
s, and cast back to a pointer. Remember though, that this solution needs huge care about the pointer arithmetic and is something you really should never do.
Subtracting two pointers gives you the distance between them. What would the result of adding two pointers be?
Lets say you have 2 pointers and you know one or both of them are null. You want to return the one that is not null or null in case both are null. The easiest way would be to sum/xor them. This is the propper case to sum pointers.