问题
I want to swap two local variables using the xor algorithm, however it will not allow me to change the address of the variables. If I create pointers to the variables, it will allow it, but is it possible to do this without using pointers?
I am trying to do this
Point a = Point();
Point b = Point(1,1);
&a ^= &b;
&b ^= &a;
&a ^= &b;
This is the closest I have been able to get to what I want to do
Point a = Point();
Point b = Point(1,1);
Point *a_ptr = &a;
Point *b_ptr = &b;
a_ptr = (Point *)(((unsigned long)a_ptr) ^ (unsigned long)b_ptr);
b_ptr = (Point *)(((unsigned long)a_ptr) ^ (unsigned long)b_ptr);
b_ptr = (Point *)(((unsigned long)a_ptr) ^ (unsigned long)b_ptr);
// The pointers are switched, but this will not work
&a = a_ptr;
回答1:
C language variables don't exist at runtime like variables in higher-level languages. Local variable "a" means, to the compiler, "the address of the stack frame - 2", or whatever it is. This reference exists only at compile time, and is fixed by the declaration. At runtime, the generated code simply fetches from the hard-coded address. So making the variable point to a different place with code is trying to change something that doesn't exist.
回答2:
The only way that it would be possible is if you actually did the xor swap on the values of the point. In your code it seems like you are trying to set the address of a value on the stack which you cannot do.
What I recommend is using std::swap
.
http://en.cppreference.com/w/cpp/algorithm/swap.
To use this your object will gave to be moveContructible and moveAssignable.
So in short no, exactly what you want to do is not possible because you cannot assign to the address of a variable. But you can achieve a similar effect in multiple ways using the values of point, making pointers or std::swap
来源:https://stackoverflow.com/questions/17460360/changing-the-address-of-a-local-variable