-2

Lets say we have an iterator (iter) over a list of pointers to memory assigned to heap space, if I do that

delete (*iter++)

am I right that the precedence is first dereference iterator to get memory address then free the space and then increment the iterator to free the next element ?

user1845360
  • 847
  • 2
  • 12
  • 29
  • Do not write code that requires too much though to figure out what is going on - better to spread it over a few lines. That way you will prevent errors either now or in the future. – Ed Heal Mar 08 '13 at 13:47
  • Just to make sure I understand what is going on behind the scenes... – user1845360 Mar 08 '13 at 13:56

4 Answers4

4

Although ++ has higher precedence than *, the side effects of post-increment ++ are applied after the dereference operator * has used the iterator's value. That is the behavior of the post-increment, or suffix ++, (as opposed to the pre-increment, or prefix ++). This rule applies to iterators as well as the "plain" pointers.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

The effect is as you write, but it's achieved using a slightly different sequence:

  1. The post-increment has highest precedence, so it's evaluated first. However, its return value (which is processed by further operators) is the value of iter before the increment.

  2. Dereference is evaluated next, returning pointer to which the non-incremented value of iter was "pointing."

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

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
1

The precedence is actually the reverse, and if the iterator is of class type (with overloaded operators) this is the order of calls to the operator functions:

  • The increment operator is called to increment the iterator. It returns a copy of itself before the increment.
  • The dereference operator is called on the temporary iterator and returns the value of the list item to which iter used to call.
  • The pointer just returned is deleted, i.e. the pointed-to object is destructed and then the memory freed.
JoergB
  • 4,383
  • 21
  • 19
0

The line is equivalent to this:

delete (*(iter++))

But since postfix increment returns the original value, you are still dereferencing the original value of iter. Therefore, if iter points at a pointer to a dynamically allocated object, the delete will destroy that object. Then iter will be left pointing to the next pointer along.

Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324