What does "*ptrInt ++" do?
I'm implementing a template pointer wrapper similar in functionaltiy to boost::shared_ptr
.
I have a pointer to an integer ptrInt
.
What I w开发者_JAVA百科ant 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:
- What exactly does
*ptrInt ++;
do? - Is there a more elegant solution to using
*ptrInt += 1;
?
*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
*ptr++
equivalent to *(ptr++)
*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.
(*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.
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++)
.
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)?
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.
*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.
精彩评论