C ++ operator priority

Suppose we have an iter over the list of pointers to memory assigned to heap space if I do this

delete (*iter++) 

Am I right that the priority is the first dereferencing iterator to get the memory address, then free up space, and then increase the iterator to free up the next item?

-2
source share
4 answers

The effect is as you write, but this is achieved with a slightly different sequence:

  • Post-increment has the highest priority, so it is evaluated first. However, its return value (which is processed by additional operators) is the iter value before the increment.

  • Next, the difference is calculated, returning the pointer to which the uninstrumented value of iter was pointing.

  • delete is evaluated last, and the pointer is deleted.

+3
source

Although ++ has a higher priority than * , the side effects of post-increment ++ apply after the dereference operator * used the value of the iterator. This is the behavior of incremental increment or suffix ++ (as opposed to pre-increment or prefix ++ ). This rule applies to iterators as well as to "simple" pointers.

+4
source

The priority is actually the opposite, and if the iterator has a class type (with overloaded operators), this is the order of operator function calls:

  • The increment operator is called to increase the iterator. It returns a copy of itself to .
  • The dereference operator is called on a temporary iterator and returns the value of the list item to which iter was used.
  • The just returned pointer is deleted, i.e. the deleted object is destroyed, and then memory is freed.
+1
source

The line is equivalent to this:

 delete (*(iter++)) 

But since postfix increment returns the original value, you are still looking for the original iter value. Therefore, if iter points to a pointer to a dynamically allocated object, delete destroy that object. Then iter will remain a pointer to the next pointer.

0
source

All Articles