const_cast [TODO]

const_cast

three examples to explain the usage of const_cast

[Code]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*************************************************************************
> File Name: mod_const.cpp
> Author: zyy
> Mail: zyy34472@gmail.com
************************************************************************/


#include <stdio.h>
#include <iostream>
using namespace std;

#define NAME2STR(_VAR_) (#_VAR_)
#define OUT(_VAR_) cout << NAME2STR(_VAR_) << ": " << _VAR_ << endl

int main (int argc, char** argv)
{

cout << "const_cast" << endl << endl;
const volatile int a1 = 1;
int &b1 = const_cast<int&>(a1);
cout << "[const volatile int -> int&]" << endl;
OUT(((&a1) == (&b1)));
OUT(&a1);
printf("But use printf, &a = %p\n", &a1);
OUT(&b1);
b1 = 2;
OUT(a1);
OUT(b1);
cout << endl << endl; ;

const int a2 = 1;
int &b2 = const_cast<int&>(a2);
cout << "[const int -> int&]" << endl;
OUT(((&a2) == (&b2)));
OUT(&a2);
OUT(&b2);
b2 = 2;
OUT(a2);
OUT(b2);
cout << endl << endl;

int a3 = 1;
const int &b3 = a3;
int &x = const_cast<int&>(b3);
cout << "[int -> const int&]" << endl;
//int* const b2 = &a2;
OUT(&a3);
OUT(&x);
x = 20;
OUT(a3);
OUT(x);
cout << endl << endl;

return 0;
}

[Result]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const_cast

[const volatile int -> int&]
((&a1) == (&b1)): 1
&a1: 1
But use printf, &a = 0x7ffeeccb8354
&b1: 0x7ffeeccb8354
a1: 2
b1: 2


[const int -> int&]
((&a2) == (&b2)): 1
&a2: 0x7ffeeccb8358
&b2: 0x7ffeeccb8358
a2: 1
b2: 2


[int -> const int&]
&a3: 0x7ffeeccb835c
&x: 0x7ffeeccb835c
a3: 20
x: 20

[Explaination]

1
To be continue ...
Express grateful thanks to Hao ren
Contents
  1. 1. const_cast
    1. 1.1. [Code]
    2. 1.2. [Result]
    3. 1.3. [Explaination]
      1. 1.3.0.0.1. Express grateful thanks to Hao ren