push-back

Is it safe to push_back an element from the same vector?

偶尔善良 提交于 2019-11-26 09:17:26
问题 vector<int> v; v.push_back(1); v.push_back(v[0]); If the second push_back causes a reallocation, the reference to the first integer in the vector will no longer be valid. So this isn\'t safe? vector<int> v; v.push_back(1); v.reserve(v.size() + 1); v.push_back(v[0]); This makes it safe? 回答1: It looks like http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-closed.html#526 addressed this problem (or something very similar to it) as a potential defect in the standard: 1) Parameters taken by const