Reputation: 81
I'm implementing a template pointer wrapper similar in functionaltiy to boost::shared_ptr
.
I have a pointer to an integer ptrInt
.
What I want to do: Increment the integer ptrInt points to.
My initial code was this: *ptrInt ++;
, although I also tried the same using (*ptrInt) ++;
Apparently, however, this doesn't seem to do what I expected it to.
In the end I got it working using *ptrInt += 1;
, however I'm asking myself:
*ptrInt ++;
do?*ptrInt += 1;
?Upvotes: 8
Views: 418
Reputation: 1724
(*ptr)++ should do it, unless you are using its value right away. Use ++*ptr then, which is equivalent to ++(*ptr) due to right-to-left associativity.
On a side note, here is my smart pointer implementation, perhaps it can help you in writing your own.
Upvotes: 1
Reputation: 1419
*ptrInt ++
will
increment ptrInt by 1
dereference old value of ptrInt
and (*ptrInt) ++
as well as *ptrInt += 1
will do what you want.
See Operator Precedence.
Upvotes: 3
Reputation: 11648
The more elegant way is whatever you tried before. i.e (*ptrInt) ++;
Since, you aren't satisfied with that, it might be because of the post - increment.
Say, std::cout<<(*ptrInt) ++;
would have shown you the un-incremented value.
So, try giving ++(*ptrInt);
which might behave as you expected.
Upvotes: 0
Reputation: 12479
You want (*ptrInt)++
, which increments the object, which generally does the same as *ptrInt += 1
. Maybe you have overloaded the +=
operator, but not the ++
operators (postfix and prefix increment operators)?
Upvotes: 0
Reputation: 5005
The expression is evaluated using the rules for operator precedence.
The postfix version of ++
(the one where ++
comes after the variable) has a higher precedence than the *
operator (indirection).
That is why *ptr++
is equivalent to *(ptr++)
.
Upvotes: 0
Reputation: 96258
*ptrInt++
in your case does increment the pointer, nothing more (before that it fetches the value from the location at throws it away. of course if you use it in a more complex expression it will use it)
(*ptrInt)++
does what you are looking for.
Upvotes: -1
Reputation: 146053
*p++ // Return value of object that p points to and then increment the pointer
(*p)++ // As above, but increment the object afterwards, not the pointer
*p += 1 // Add one to the object p points to
The final two both increment the object, so I'm not sure why you didn't think it worked. If the expression is used as a value, the final form will return the value after being incremented but the others return the value before.
x = (*p)++; // original value in x
(*p)++;
x = *p; // new value in X
or
x = ++*p; // increment object and store new value in x
Upvotes: 9