Is iter++->empty() a legal expression?

允我心安 提交于 2021-02-08 08:06:32

问题


Is iter++->empty() a legal expression?

iter is an iterator of a vector of strings.

I am asking because considering the precedence of the operators both -> and () should precede the postfix increment but I really don't know how the operands should be grouped.

On my compiler it works (the expression yields the empty() result for the first string and iter points to the second string) but I'm still wondering if it is Undefined Behaviour.

Edit

I just found the solution (I think):

iter++->empty() should be the same as (*iter++).empty()

therefore considering associativity and precedence rules the grouping should be:

(((*(iter++)).empty) ())

Is that correct?


回答1:


It's legal, but don't do it.

Asking yourself this question is reason enough to break it into two statements:

iter->empty();
iter++;



回答2:


Assuming the iterator it is valid, the expression it++->empty() is well-defined




回答3:


Assuming that iter->empty() is a valid statement, the answer is yes. The post-increment operator doesn't change the type of iter, is simply increments it after the empty() method has been performed.

However, I'd recommend splitting it up into two statements, as (especially post-) increment statements often make your code less clear. So why not go for:

iter->empty();
iter++;


来源:https://stackoverflow.com/questions/19765623/is-iter-empty-a-legal-expression

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