Constly Const Pointer

受不了了啊!指针与常量!别搁那“就近原则”了!来点从编译器视角的解析吧!

Define

1
2
3
4
5
6
struct FRegirtry {
int v = 0;
void Set(int n) {v = n;} // non-const method
int Get() const {return v;} // const method
};
using FR = FRegistry;

Show me the memory

1
2
3
4
5
6
7
8
9
10
FR r;
const FR cr;

r.Set(1);
r.Get();
// cr.Set(1); // ERROR: cant set to const value
cr.Get();

r = FR();
// cr = FR(); // ERROR: cant use the Copy constructor

Just a ptr, inherit value’s constant feature

1
2
3
4
5
6
7
8
9
10
FR* pr = &r;
// FR* pcr = &cr; // ERROR: cant create mutable ponter to a constant value

pr->Get();
pr->Set(1);
// pcr->Get();
// pcr->Set(1);

pr = &r;
// pcr = &cr;

Constly ptr to a value, but ptr is not const

1
2
3
4
5
6
7
8
9
10
11
12
const FR* cpr = &r;
const FR* cpcr = &cr;

cpr->Get();
// cpr->Set(1); // ERROR: const ptr cant use non-const method
// cpr->c = 3; // ERROR: an immutable left value
int c = cpr->c; // OK: read as ref
cpcr->Get();
// cpcr->Set(1);

cpr = &r; // OK: ptr object is not const :)
cpcr = &cr;

Const ptr to a value

1
2
3
4
5
6
7
8
9
10
FR * const prc = &r;
// FR * const pcrc = &cr; // ERROR: const ptr, but mutable to value

prc->Get();
prc->Set(1);
// pcrc->Get();
// pcrc->Set(1);

// prc = &r; // ERROR: cant assign to a const value, btw its type is ptr
// pcrc = &cr;

Constly const ptr to a value

1
2
3
4
5
6
7
8
9
10
const FR * const cprc = &r;
const FR * const cpcrc = &cr;

cprc->Get();
// cprc->Set(1);
cpcrc->Get();
// cpcrc->Set(1);

// cprc = &r;
// cpcrc = &r;
Share