正文内容
C++ const 用法详解
const 用来修饰只读,被const修饰的变量/指针/引用/成员/函数,不能被修改。核心一句话:const 修饰谁,谁就不可改。
区分两个概念:
- 顶层const:对象本身不可修改
- 底层const:指向的内容不可修改
一、const 修饰普通变量
const int a = 10;
a = 20; // ❌ 编译报错,a只读
// const变量必须初始化
const int b; // ❌ 错误,没有初始值
int c = 100;
const int d = c; // ✅ 可以,运行期初始化
C++中
const int a在局部作用域默认不是编译期常量;想要编译期常量用constexpr。
constexpr int num = 20; // C++11,编译期常量
二、const 修饰指针(重点,极易混淆)
口诀:看const离谁近,就锁住谁
// 1. const 在 *前面:锁住指针指向的数据(底层const)
const int* p1;
int const* p2; // 和上一行完全等价
*p1 = 100; // ❌ 不能改内容
p1 = &other; // ✅ 指针本身可以改,指向别的地址
// 2. const 在 *后面:锁住指针本身(顶层const)
int* const p3 = &val;
*p3 = 200; // ✅ 内容可改
p3 = &other; // ❌ 指针本身不能改,不能换指向
// 3. *前后都有const:指针和内容都不能改
const int* const p4 = &val;
*p4 = 99; // ❌
p4 = &other; // ❌
指针和const补充
const int*:常指针,指向常量,不能通过指针修改值int* const:常量指针,指针本身固定,不能换地址
三、const 修饰引用(const引用)
int x = 10;
const int& r = x;
r = 20; // ❌ 不能通过引用修改x
x = 20; // ✅ x本身不是const,可以直接修改
// 可以绑定临时变量,普通引用不行
const int& ref = 100; // ✅ 合法
int& ref2 = 100; // ❌ 普通引用不能绑定临时值
const引用最常用场景:函数传参,避免拷贝,又防止修改实参。
四、const 修饰函数参数
目的:保证函数内部不会修改传入的参数,减少拷贝。
// 推荐:const引用,大对象优先使用
void func(const std::string& s){
// s不能修改
}
// const指针
void func(const int* p){
// *p不可修改
}
五、const 修饰成员函数(类里面最重要)
const成员函数:承诺不修改类的成员变量,
this指针变成const 类名* const this
class Test{
public:
int val = 10;
// const成员函数
void show() const {
// val = 20; ❌ 不能修改普通成员
std::cout << val;
}
void setVal(int v){
val = v;
}
};
int main(){
Test t1;
t1.show(); // ✅ 普通对象可以调用const成员
const Test t2;
t2.show(); // ✅ const对象只能调用const成员函数
t2.setVal(5); // ❌ const对象不能调用非const成员
}
mutable 突破const成员函数
mutable修饰的成员变量,在const成员函数中依然可以修改
class Test{
public:
mutable int cnt = 0;
void show() const {
cnt++; // ✅ mutable变量可以修改
}
};
适用场景:缓存、计数、日志标记,不影响对象对外语义。
六、const 修饰函数返回值
- 返回普通值:
const int func(),const无意义,返回值拷贝,加const没用 - 返回const引用:最常用,避免拷贝,禁止外部修改返回对象
const std::string& getName(){
return name;
}
- 返回const指针:
const int* getPtr(),调用者不能通过指针修改内容
注意:不要返回局部变量的引用/指针,不管加不加const。
七、const 全局变量
const int g_val = 100;
C++中全局const默认内部链接属性(仅当前文件可见),和普通全局变量不同。 想要跨文件使用:
extern const int g_val;
八、const 和指针的类型匹配规则
- 非const指针不能直接指向const变量
const int a = 10;
int* p = &a; // ❌ 编译报错,会有风险:通过p修改a
const int* p = &a; // ✅ 正确
可以理解:不能丢掉底层const,可以添加const。
九、const / constexpr / consteval 简单对比
| 关键字 | 作用 |
|---|---|
| const | 只读,可运行期初始化 |
| constexpr(C++11) | 编译期常量,编译阶段求值,也能用于函数 |
| consteval(C++20) | 强制编译期求值,只能编译期调用 |
constexpr int add(int a,int b){
return a+b;
}
int arr[add(1,2)]; // ✅ 编译期求值,用来定义数组大小
十、const 常见坑总结
const int *p和int *const p极易写反,记住离*远近规则- const对象只能调用const成员函数
- const成员函数内,普通成员变量不能修改,mutable除外
- 普通引用不能绑定临时值,const引用可以
- 顶层const在函数传参时会被编译器忽略,
void func(const int)等价void func(int) - const不代表编译期常量(C++11后用constexpr才是)
十一、使用建议
- 能加const就加const,让编译器帮你检查意外修改,提高代码健壮性
- 类成员函数,不修改成员的一律写成
const - 函数参数:大对象优先
const &,避免拷贝 - 返回对象时,如果不需要外部修改,返回
const&
正文内容已启用复制保护,代码块与行内代码仍支持复制。
读者留言
还没有评论,来发表第一条评论吧。