I was reviewing some code. There I saw this:
int Obj::GetValue() const
{
return m_val;
}
void SomeFunc(const Obj *obj1)
{
// keep a copy in case obj1 is modified!
const Obj o2 = *obj1;
//... much more code
// some which may modify data pointed to by obj1
DoSomething(o2.GetValue()); // use original value!
}
can a compiler optimize this code such that o2.GetValue() will end up being replace by obj1->GetValue() or some cached value ?
Obj1 points to some memtable, the pointer remains valid through the function, but the memtable data can change synchronously due to some call within the function that operate on the memtable which incidentally is global! this is why the dev took a copy of Obj1, but because he was not planning on modifying it he decided to declare it const.
I think that because we point to a const object, and the copied object is const then the optimiser can decide to optimize out the copy
I've checked with godbolt.org using: gcc, clang & msvc as our code is multi platform, and all seems good. But of course if this code is UB, I will ask for it to be changed.