4 ms·
That's not always true. struct X { const int i{123}; const int j; X(int j_) : j{j_} {} }; // non-const object; x.i == 123; x.j == 111 X x
by frankzinger 9y ago
That's not always true.
struct X {
const int i{123};
const int j;
X(int j_) : j{j_} {}
};
// non-const object; x.i == 123; x.j == 111
X x{111};
x.i = 222; // compilation error
x.j = 333; // compilation error
- frankzinger 9y agoAnd a more idiomatic example: struct X { X(Y val) : y_{val} {} // Can be called on const and non-const X objects const Y& y() const { return y_; } // Can only be called on non-const X objects Y& y() { return y_; } private: Y y_; }; void f(X& x) { x.y() = 222; } void g(const X& x) { x.y() = 222); } const X x{123}; // x.y() == 123 x.y() = 222; // compilation error f(x); // compilation error (f's parm is non-const) g(x); // compilation error (can't assign to const ref) // Cannot take non-const ref or ptr of x X& xr{x}; // compilation error X* xp{&x}; // compilation error If the original declaration of the variable is const nothing can modify it. (And as my first example shows, the original declaration can always be const if you want it to be, regardless of context.) You can't take a non-const pointer or reference to x without explicitly circumventing the language like this: X& xr{const_cast<X&>(x)}; X* xp(const_cast<X*>(&x)};
- pcwalton 9y agoSure, if the object was declared const in the first place, then it (mostly) can't be mutated. But the real power of const comes from const references, which in Rust guarantee that the referenced object will not be mutated while the reference is alive, even though it might have been mutated before.
- frankzinger 9y agoI see. That's a nice feature.