Is it legal to use the increment operator in a C++ function call?

前端 未结 8 1274
时光取名叫无心
时光取名叫无心 2020-11-30 01:56

There\'s been some debate going on in this question about whether the following code is legal C++:

std::list::iterator i = items.begin();
while          


        
相关标签:
8条回答
  • 2020-11-30 02:32

    The standard says the side effect happens before the call, so the code is the same as:

    std::list<item*>::iterator i_before = i;
    
    i = i_before + 1;
    
    items.erase(i_before);
    

    rather than being:

    std::list<item*>::iterator i_before = i;
    
    items.erase(i);
    
    i = i_before + 1;
    

    So it is safe in this case, because list.erase() specifically doesn't invalidate any iterators other than the one erased.

    That said, it's bad style - the erase function for all containers returns the next iterator specifically so you don't have to worry about invalidating iterators due to reallocation, so the idiomatic code:

    i = items.erase(i);
    

    will be safe for lists, and will also be safe for vectors, deques and any other sequence container should you want to change your storage.

    You also wouldn't get the original code to compile without warnings - you'd have to write

    (void)items.erase(i++);
    

    to avoid a warning about an unused return, which would be a big clue that you're doing something odd.

    0 讨论(0)
  • 2020-11-30 02:32

    It's perfectly OK. The value passed would be the value of "i" before the increment.

    0 讨论(0)
提交回复
热议问题