问题
Is iter++->empty()
a legal expression?
iter
is an iterator
of a vector
of string
s.
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