std::vector<int> a;
a.push_back(1);
a.push_back(a[0]);
I just learned that the code above can be very dangerous.
(If it's not obvious why, you're not alone... it wasn't obvious to me either.)
My questions:
What is the "standard" way of dealing with it? Making a new variable and then assigning it immediately to something afterward seems a bit weird to me. Is there a better way of dealing with it?
How do you train yourself to watch out for aliasing issues like this? What pattern(s) do you look for? I have no idea to recognize this situation; I only learned about aliasing when I learned about the
restrict
keyword in C, and only now do I understand what the issue really is.
Edit:
I'd love to accept an answer, but it doesn't seem like part (2) of the question has been answered. I'm wondering what strategies people use to locate aliasing mistakes in code they have written.
One strategy I've come up with so far is to avoid passing in the same value for in two parameters. (In this case, one parameter is implicit and one explicit.)
Are there any other easy things to notice and watch out for?
a[0]
? – Homespuna[0]
will be invalidated during the operation, but it will be invalidated after the element is copied, which means that at the time of access toa[0]
(as parameter topush_back
) that object is still alive. Additionally the exception guarantees require that all elements are copied to the new location (including the newly inserted) before freeing the old buffer, as the container cannot guarantee that copy construction will not throw, and if it throws the vector must be left in the original state. – Tractarianismdelete
the pointer is invalid but it still exists. The UB is not that on the existence of the invalid reference/pointer, but rather in accessing it. – Tractarianismdelete
, you may not access the pointer anyway, so theoretically it could be zero'd bydelete
and hence made safe?) I've seen this question pop up more than once... and when I expressed my surprise someone told me I'm indeed wrong, and that the only valid pointers are those that point to an array or 1 element past. – Haileyhailfellowwellmet