0
class T {
public:
    int v;
    int &vRef;
public:
    T() : v(0), vRef(v) {}
};

const T t; // note, it's a const object
t.vRef = 2;
printf("v: %d\n", t.v);

The code presented above compiles OK, and the const object's internal value did change.

Question. Is this Undefined Behavior or not?

Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
ZSaberLv0
  • 237
  • 1
  • 7
  • 1
    Yes and it makes sense too. On some processor architectures a const variable could be put into some unmodifiable piece of RAM (with readonly rights) or even ROM. – Pepijn Kramer Dec 03 '22 at 06:30
  • Yes. Modifying a non-`mutable` member of a `const` object by any means gives undefined behaviour. If you really want to modify a member of a `const` object without undefined behaviour, then make it `mutable`. In your case, that means `v` should be `mutable` and you have no need for `vRef`. – Peter Dec 03 '22 at 07:01
  • 1
    Worth noting that an object under construction (before the constructor of the most derived object ends) is not const yet (https://eel.is/c++draft/class#ctor.general-5) so you can modify `v` and `vRef` inside the body of the constructor – Artyer Dec 03 '22 at 10:32

1 Answers1

3

Yes. If the object is declared as const, then modifying it (through any means, be that a non-const reference like in your example, via const_cast or something else) is UB.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70