c++ - 消除变量的 const 拷贝

标签 c++ undefined-behavior

我正在审查一些代码。我在那里看到了这个:

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!
}

编译器可以优化此代码,以便 o2.GetValue() 最终被 obj1->GetValue() 或某些缓存值替换吗?

Obj1指向某个memtable,指针通过该函数仍然有效,但是由于函数内对memtable进行操作的某些调用,memtable数据可以同步更改,而顺便说一句,memtable是全局的! 这就是开发人员复制 Obj1 的原因,但因为他不打算修改它,所以决定将其声明为 const。

我认为因为我们指向一个const对象,并且复制的对象是const,那么优化器可以决定优化拷贝

我已经使用 gcc、clang 和 msvc 与 godbolt.org 进行了检查,因为我们的代码是多平台的,一切看起来都很好。但当然,如果这个代码是UB,我会要求更改它。

最佳答案

can a compiler optimize this code such that o2.GetValue() will end up being replace by obj->GetValue() or some cached value ?

如果编译器能够保证优化遵循as-if rule它可以做这样的优化。

如果它能做到这一假设取决于实际做了什么:

   //... much more code
   // some which may modify data pointed to by obj1

关于c++ - 消除变量的 const 拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68908480/

相关文章:

c++ - 关于对齐存储和普通可复制/可破坏类型

c++ - 为什么我不应该尝试在 "this"之后使用 "delete this"值?

c++ - 引用列表元素然后弹出它,它是未定义的行为吗?

c++ - 如何将用户返回到模拟之前的状态?

c++ - 递归地删除连续的重复项,给出无限递归

c++ - 对 __cxa_end_cleanup' 的 undefined reference

c++ - "undefined-ness"修改 const 值的机制

c++ - 未定义的行为和顺序点

C++ 模板元编程,成员变量的数量?

c++ - 加密程序错误