Home >Backend Development >C++ >When Pushing Elements from the Same Vector, Is it Safe to Rely on the Original Reference?

When Pushing Elements from the Same Vector, Is it Safe to Rely on the Original Reference?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-24 10:33:301052browse

When Pushing Elements from the Same Vector, Is it Safe to Rely on the Original Reference?

Pushing Back Elements from the Same Vector: A Cautionary Tale

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn