C++ Const-ness Noodle
We have been working with Javascript at the day job. I found it odd that const x = {a:1,b:2}
did not make the value of the object immutable. I found it even more odd that Javascript has Object.freeze()
which does make the value immutable. Why is that not the default when declaring const x
?
This prompted me to revisit Good Ole C++ to see if my recollection of const-ness there was accurate. It is.
Here’s a snippet that you can paste into Compiler Explorer to show it for the simple case of a struct.
#include <vector>
#include <iostream>
int main() {
typedef struct T { int a; int b;} T;
T x = {1,2};
const T y = {3,4};
T* px = &x;
// T* py = &y; //error, cannot assign const y to non-const
const T* cpx = &x;
const T* cpy = &y;
const T* const cpcx = &x;
const T* const cpcy = &y;
T& rx = x;
// T& ry = y; //error, cannot assign const y to non-const
const T& crx = x;
const T& cry = y;
std::cout << x.a << x.b
<< y.a << y.b
<< px->a << px->b
// << py->a << py->b
<< cpx->a << cpx->b
<< cpy->a << cpy->b
<< cpcx->a << cpcx->b
<< cpcy->a << cpcy->b
<< rx.a << rx.b
// << ry.a << ry.b
<< crx.a << crx.b
<< cry.a << cry.b
;
x.a = 42;
// y.a = 42; //error
px->a = 42;
// py->a = 42; //error
// cpx->a = 42; //error
// cpy->a = 42; //error
// cpcx->a = 42; //error
// cpcy->a = 42; //error
rx.a = 42;
// ry.a = 42;
// crx.a = 42; // error
// cry.a = 42; //error
}