Is it legal to add elements to a preallocated vector in a range-based for loop over that vector?

后端 未结 2 379
灰色年华
灰色年华 2021-01-03 22:30

I\'m using Visual Studio 2015 Update 1 C++ compiler and this code snippet:

#include 
#include 

using namespace std;

int main(         


        
2条回答
  •  有刺的猬
    2021-01-03 22:52

    According to documentation:

    If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.

    It says even if capacity is enough past-the-end iterator is invalidated, so I believe your code has UB (unless this documentation is incorrect and standard says otherwise)

提交回复
热议问题