Vector Push_Back and Reference Validity
When inserting elements into a vector using push_back, it's crucial to consider the potential impact on references to existing elements. Here we examine the safety of push_back under specific conditions.
Consider the following example:
<code class="cpp">vector<int> v; v.push_back(1); v.push_back(v[0]);</code>
In this case, if the second push_back triggers a reallocation, the address of v[0] becomes invalid due to vector movement. This poses a potential safety issue.
To mitigate this, one can employ reserve:
<code class="cpp">vector<int> v; v.push_back(1); v.reserve(v.size() + 1); v.push_back(v[0]);</code>
In this modified code, the reserve ensures that the allocated memory is sufficient to accommodate the new element without reallocation, preserving the validity of references.
It is worth noting that the C standard has addressed concerns similar to this as potential defects. However, the resolution concluded that these operations are allowed behavior:
v.insert(v.begin(), v[2]);
The rationale is that the standard implicitly permits such operations to succeed, ensuring that vectors remain a reliable data structure for managing and manipulating large collections.
The above is the detailed content of Is Vector Push_Back Safe for Element References?. For more information, please follow other related articles on the PHP Chinese website!