Home > Backend Development > C++ > body text

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

Mary-Kate Olsen
Release: 2024-10-24 10:33:30
Original
981 people have browsed it

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>
Copy after login

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>
Copy after login

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
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!