C++ operator precedence

╄→гoц情女王★ 提交于 2019-12-14 03:29:17

问题


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 ?


回答1:


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.




回答2:


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.




回答3:


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.



回答4:


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.



来源:https://stackoverflow.com/questions/15295226/c-operator-precedence

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!