3 ms·
struct X { int i; }; X* p; void bar(X x){ P->i=1; assert(x.i==0);// fails with transparent pass by ref } void foo() { X x{0}; P=&x;
by gpderetta 6y ago
struct X { int i; };
X* p;
void bar(X x){
P->i=1;
assert(x.i==0);// fails with transparent pass by ref
}
void foo() {
X x{0};
P=&x;
bar(x);
}
- Negitivefrags 6y agoThe compiler knows that there is a mutable pointer to x floating around as soon as you did `P=&x`. Therefore it knows it needs to make a new copy of x and then pass an immutable pointer to that value when calling `bar`. This is something the compiler already keeps track of anyway in order to be able to know if it needs to re-load variables from memory when they are used again after a function call. Basically the optimsiation degrades to exactly what happened before in the case where you do this.
- gpderetta 6y agoIn many cases you might need to make two copies. Also remember, the author proposes to change the abi to encourage pass by value instead of of pass by restricted reference, so in the original code there might be zero copies. In practice this optimization would be very fragile (like most optimizations relying on escape analysis) and people would keep passing by reference in fear that a small change like taking the address of an object might force a copy of a large struct.
- mort96 6y agoWell, no, that's just one of the situations where the compiler would have to make a copy in the callee; a write to a pointer which might alias the argument.