开发者

c++ what does "iter = ++iter" do? is it valid?

I have a question on c++ std iterators.

suppose iter is std::set<SomeType>::iterator type.

Is:

iter = ++iter 

the same as:

++iter 

or are they different?


edit:

I found a code std::set<UserDefinedClass*>::iterator being used that way. (pointer)

I wonder if that can cause the program I'm debugging开发者_C百科 malfunction.

I'm reading up the answers but it's hard to judge which answer is correct.


There's no definitive answer to this question. The answer depends on the nature of std::set<SomeType>::iterator type. If it is a user-defined type (i.e. a class with overloaded operators), then the behavior of iter = ++iter is defined ans is indeed equivalent to a mere ++iter. However, if std::set<SomeType>::iterator is a built-in type, then iter = ++iter produces undefined behavior, since it modifies the same object twice in one expression without an intervening sequence point (violation of the requirements presented in 5/4 of the language standard).

So, theoretically in general case one should avoid doing something like that since in general case the behavior is undefined. In practice though std::set<SomeType>::iterator will normally be a user-defined type and iter = ++iter will work. Nevertheless this is not a reason to use such expressions in the code.


Yes they are the same thing - but why do this?


Yes, same thing. A simpler case, same thing:

int i = 10;   //i = 10
int j = i++;  //j = 10
int k = ++i;  //k = 12

However

i = ++i; 

is unnecessary as it increments i and then assigns i to i

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜