1. const指针和指向const的指针
- 指向const的指针是在类型前加星号
可以指向非const类型
指针可以改变指向
dereference不能改变值 - const指针是在类型后面加星号
指针不可以改变指向
dereference可以改变值
参考learncpp的内容
To summarize, you only need to remember 4 rules, and they are pretty logical:
- A non-const pointer can be assigned another address to change what it is pointing at
- A const pointer always points to the same address, and this address can not be changed.
- A pointer to a non-const value can change the value it is pointing to. These can not point to a const value.
- A pointer to a const value treats the value as const when accessed through the pointer, and thus can not change the value it is pointing to. These can be pointed to const or non-const l-values (but not r-values, which don’t have an address)
Keeping the declaration syntax straight can be a bit challenging: - The pointer’s type defines the type of the object being pointed at. So a const in the type means the pointer is pointing at a const value.
- A const after the asterisk means the pointer itself is const and it can not be assigned a new address.
int main()
{
const int x{ 5 };
const int* ptr { &x }; // ptr points to const int x
const int y{ 6 };
ptr = &y; // okay: ptr now points at const int y
return 0;
}
// 指向const的指针
int main()
{
const int x{ 5 };
const int* ptr { &x }; // ptr points to const int x
const int y{ 6 };
ptr = &y; // okay: ptr now points at const int y
return 0;
}
// const 指针
int main()
{
int x{ 5 };
int y{ 6 };
int* const ptr { &x }; // okay: the const pointer is initialized to the address of x
ptr = &y; // error: once initialized, a const pointer can not be changed.
return 0;
}