What does "* ptrInt ++" do?

I implement a template pointer wrapper similar to functiontiy to boost::shared_ptr .

I have a pointer to an integer ptrInt .

What I want to do: The integer increment ptrInt points to.

My initial code was as follows: *ptrInt ++; , although I also tried the same with (*ptrInt) ++;

Apparently, however, this does not seem to do what I expected from him. In the end, I started working with *ptrInt += 1; but I ask myself:

  • What exactly does *ptrInt ++; ?
  • Is there a more elegant solution for using *ptrInt += 1; ?
+8
c ++ syntax pointers
source share
8 answers
 *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 last two enlarge 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 it has been increased, and the rest will return the value earlier.

 x = (*p)++; // original value in x (*p)++; x = *p; // new value in X 

or

 x = ++*p; // increment object and store new value in x 
+9
source share

*ptr++ equivalent to *(ptr++)

+4
source share

*ptrInt ++ will be

  • increment ptrInt by 1

  • dereference the old ptrInt value

and (*ptrInt) ++ , as well as *ptrInt += 1 will do what you want.

See Operator Priority .

+3
source share

(* ptr) ++ should do this if you are not using its value immediately. Use ++ * ptr then, which is equivalent to ++ (* ptr) because of associativity from right to left.

On the side of the note, here is my implementation of a smart pointer , perhaps this will help you write your own.

+1
source share

An expression is evaluated using rules for operator precedence.

The postfix version ++ (the one where ++ appears after the variable) takes precedence over the * (indirectness) operator.

This is why *ptr++ equivalent to *(ptr++) .

0
source share

You want (*ptrInt)++ , which increments an object that usually does the same as *ptrInt += 1 . Perhaps you overloaded the += operator, but not the ++ operators (postfix and prefix increment operators)?

0
source share

A more elegant way is that you have tried before. i (*ptrInt) ++;

Since you are not satisfied with this, it may be due to post-increment.

Let's say std::cout<<(*ptrInt) ++; would show you non-incremental value.

So try giving ++(*ptrInt); that can behave as you expected.

0
source share

*ptrInt++ in your case increases the pointer, no more (before that it extracts the value from the location when it is thrown out. Of course, if you use it in a more complex expression, it will use it)

(*ptrInt)++ does what you are looking for.

-one
source share

All Articles