7 ms·
> Unless we are talking about multiple threads here (which we aren't), there is no other code that is executing that can change what this const reference is poi
by Ace17 10y ago
> Unless we are talking about multiple threads here (which we aren't), there is no other code that is executing that can change what this const reference is pointing to.
... except if your code calls potentially 'impure' functions.
void f(const int& value)
{
const int a = value;
g();
const int b = value;
assert(a == b);
}
One can't tell if the assertion will succeed.
Indeed, 'value' might have been modified as a consequence of calling 'g'.
You don't have this uncertainity if 'value' is marked as immutable.
- DannyBee 10y ago"One can't tell if the assertion will succeed. " If value was originally a const object (IE immutable), it is well defined and guaranteed to always succeed. IE const char* myString = "Hallo World!"; const_cast<char*>(myString)[1] = 'e'; This is illegal, the same as anything modifying value would be if it was originally const. If value was originally not a const object, it wasn't immutable, so anything goes. "You don't have this uncertainity if 'value' is marked as immutable. " You can, in C++ mark the original immutable in a way that you can tell if the assertion will succeed.
- int_19h 10y agoThe compiler can't tell the difference (in general), because what it sees is a const int&, but the actual referenced object may be a non-const int.
- DannyBee 10y agoOnly in a world where people who care about performance don't hand the compiler enough of the program to make that determination (which only requires being able to see the original allocation site and the call) That's crazytown. "Please optimize this as hard as you can with two hands tied behind your back". So like i said, i don't disagree that it's a useful thing to do, i just am not sure i believe it matters in practice to people who care about performance. IE the purported benefit is already achievable and achieved, quite regularly. Again, doesn't make it less useful in general, i'm just not sure i believe it is somehow amazing for performance to people who care about performance.