我可以确定 const 引用在被另一个实体修改时会更新吗?

Can I be sure than a const reference is updated when modified by another entity?

我有一个 class Foo 有权读取 class Bar 的实例,但无权修改它。同时,Bar的实例可以被其他元素修改。

目前我是这样实现的:

class Foo
{
  private:
    const Bar& bar; // Foo can't modify it
  public:
    Foo(const Bar& bar_) : bar(bar_) {}
    void doSomthing() { this->bar.printData(); }
};

它可以这样使用:

Bar bar;
Foo foo(bar);
bar.update(); // This modify the instance of Bar
foo.doSomthing(); // This use the reference to (modified) bar

我的问题是:有了这个实现,我可以确定编译器不会使用 bar 的未更新副本,即使引用声明为 const ?

如果没有,我该怎么做?

注意:出于兼容性原因,我不使用 C++11

是的,你可以确定。引用在编译器中作为指针在内部实现,bar.update();Foo::bar 作用于相同的内存位置。

当然,只要不存在数据竞争问题,就会出现常见的同步问题。

我能很快找到的最好的 c++11 之前的标准文本是 this draft 2005 年的,它应该足够接近 C++03。

它在 3.10:13 中说 [basic.lval]

The referent of a const-qualified expression shall not be modified (through that expression), except that if it is of class type and has a mutable component, that component can be modified.

强调是我的,强调指称对象 可以 通过其他表达式进行修改(如果它们本身允许的话)。