1. const修饰变量
const int a = 10; // declare a constant
const int* pa; // variable pa pointer points to a constant not correct, should be could not change the *pa by pa.
int* const pb; // constant pointer pb points to a variable
const int* const pa; // constant pointer pc points to a constant
int *pc = &a; // error
const int* pa = &a; // ok
const int &ra = a; // ok
int &rb = a; // error
confusion:
int main()
{
const int a = 10;
int *pa = (int *) &a;
*pa = 11;
printf("*pa = %d \n", *pa);
printf("a = %d\n", a);
return 0;
}
output:
*pa = 11
a = 10
but use gdb to check value,
*pa 11
a 11
solved, 由于编译器优化,a 被存放到寄存器里面,解决方法 在前面加上volatile const int a. 或者关闭编译器优化选项。
why? could someone explain?
2. const parameter 不改变 parameter
void print(const string s);
string str("Hello world")
print(str); // ok
3. const return value
const get();
prevent users to change the return value
4. const member function
void ClassName::print(string s) const
just use in member function, it indicates that the function doesn't change the member variable
const and non-const function could overload