Why can't I add pointers?

前端 未结 7 913
终归单人心
终归单人心 2020-11-30 00:38

I have code very similiar to this:

LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator+(const Iterator& right)const
{
    return (this + &am         


        
7条回答
  •  广开言路
    2020-11-30 01:29

    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.

提交回复
热议问题