Search code examples
c++referenceconstantspass-by-referenceconst-correctness

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


I have a class Foo having the rights to read an instance of class Bar, but doesn't have the rights to modify it. In the same time, the instance of Bar could be modified by other elements.

For the moment, I implement it by this way:

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

And it could be used like this:

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

My question is: With this implementation, can I be sure than the compiler doesn't use a non updated copy of bar even if the reference is declared as const ?

If no, how can I do that ?

Note: I don't use C++11 for compatibility reason


Solution

  • Yes, you can be sure. References are internally implemented in the compiler as pointers, and both bar.update(); and Foo::bar are acting on the same memory location.

    That's, of course, as long as there are no data race concerns, at which point the usual problems of synchronization arise.