Home >Backend Development >C++ >When Pushing Elements from the Same Vector, Is it Safe to Rely on the Original Reference?
In this discussion, we investigate the potential pitfalls associated with pushing an element back from the same vector and explore techniques to ensure its safety.
Potential Hazards
Consider the following code snippet:
<code class="cpp">vector<int> v; v.push_back(1); v.push_back(v[0]);</code>
The second push_back operation may reallocate the vector, invalidating the reference to the first element. Therefore, this approach is generally considered unsafe.
Safe Approach
To ensure the safety of such operations, we can use the reserve method to allocate sufficient space in advance:
<code class="cpp">vector<int> v; v.push_back(1); v.reserve(v.size() + 1); v.push_back(v[0]);</code>
Standard Conformance
The behavior described above has been addressed in the C standard (or a similar issue):
1) Parameters taken by const reference can be changed during execution of the function Examples: Given std::vector v: v.insert(v.begin(), v[2]); v[2] can be changed by moving elements of vector
However, this issue was not considered a defect, as it is the responsibility of the vector to ensure functionality even when its contents are modified.
The above is the detailed content of When Pushing Elements from the Same Vector, Is it Safe to Rely on the Original Reference?. For more information, please follow other related articles on the PHP Chinese website!