3 ms·
No. C++ const just means "I won't mutate this object" (through the const pointer). It doesn't mean that somebody else won't mutate the some object (through thei
by pcwalton 9y ago
No. C++ const just means "I won't mutate this object" (through the const pointer). It doesn't mean that somebody else won't mutate the some object (through their non-const pointer to the same object).
- frankzinger 9y agoThat'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.
- snovv_crash 9y agoYou're thinking of a const pointer or reference. Of course if the data the pointer is pointing at changes, if you dereference it you get something else. But notice: the pointer, ie. the page number of your book, or the offset in your array, did indeed remain const. It is just the contents of the book/array that changed. So, a const value cannot be mutated locally or globally. So if you make something const and expose it, it cannot be changed.