I’m interested to know why an assignment like &a = &b is not permitted in C++.
I understand the risks in doing so, but it’s not a good enough reason to forbid it completely, to me at least. The reason why I thought about that was because I was looking for a smart way to swap big objects without copying, and something like that seemed like a good idea:
void ptr_swap( ptrdiff_t &a, ptrdiff_t &b )
{
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
int main()
{
double a = 157648.13;
double b = 96871.84;
printf("%.4f %.4f\n", a, b);
ptr_swap( reinterpret_cast<ptrdiff_t>(&a), reinterpret_cast<ptrdiff_t>(&b) );
printf("%.4f %.4f\n", a, b);
}
.. but apparently, the compiler doesn’t think so. 🙁
EDIT: I understand why this doesn’t work. Maybe my question would be clearer like that: I don’t know how many properties a variable has in a program, but at least a name, a value, an address, and some indication of its lifetime perhaps. The thing is that to me, swapping is essentially renaming two existing values stored in memory, and it’s nonsense that it would incur a copy.
With this “horrific” code example that I gave up there, what I’m trying to do is to say to the compiler: “From now on, b is named a, and vice-versa”. Why is such a thing not possible? The motivation is that it’s already possible to “instruct the compiler” in a way, via TMP for instance, so why not like that too?
It seems to me like you want to change the address of an object, right? That is impossible. Every object has a fixed address through its entire lifetime. You cannot give a different address to an object, ever. The address of an object is implicit in the machine code that’s generated, it’s not stored anywhere per se.