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?