Pushing Elements from the Same Vector: Safety Measures
The safety of pushing back an element from the same vector hinges on the potential for reallocation, which can invalidate references to existing vector elements. This issue arises in the following example:
vector v;
v.push_back(1);
v.push_back(v[0]);
If the second push_back triggers reallocation, the reference to v[0] becomes invalid. To address this, the following approach can be used:
vector v;
v.push_back(1);
v.reserve(v.size() 1);
v.push_back(v[0]);
By calling reserve, we explicitly request sufficient memory, ensuring that no reallocation occurs during subsequent insertions.
According to the C standard, the behavior of push_back with respect to element references is not explicitly defined as a defect, even though it could potentially lead to invalid references. This is because the standard requires vector::insert to work correctly, even when the insertion changes the positions of other elements.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3