const 正确性陷阱¶
const 正确性不是“编译器不报错就一直加 const”。它改变的是:哪些操作合法、
哪些对象可以被修改,以及临时对象能活多久。下面三个失败模式之所以常见,
是因为它们第一眼看上去都像是对的。
可运行配套示例:
1. 引用可以延长临时对象,指针不行¶
const std::string& ref = std::string("temporary"); // lives as long as ref
const char* ptr = std::string("temporary").c_str(); // dangles after this line
把临时对象绑定到 const 引用会把临时对象的生命周期延长到引用的作用域,
所以 ref 是安全的。c_str() 返回的是指向临时对象缓冲区的指针,而指针
不会延长临时对象的生命周期;完整表达式结束后,ptr 指向的存储已经失效。
标准规则在 [class.temporary](临时对象与生命周期延长)。关键区别是
引用绑定,不是“const 让它安全”:
const std::string& ref = std::string("temporary");——生命周期被延长const char* ptr = std::string("temporary").c_str();——没有延长
string_view 也是同一个道理:view 不拥有字符。CI 验证版本见
悬垂 string_view 图谱条目。
2. mutable 让写入合法,但不让写入线程安全¶
class Cache {
public:
int get(int key) const {
auto it = cache_.find(key);
if (it != cache_.end()) return it->second;
int value = compute(key);
cache_[key] = value; // legal because cache_ is mutable
return value;
}
private:
mutable std::map<int, int> cache_;
int compute(int key) const;
};
这是合法的 C++。const 成员函数承诺不通过非 mutable 路径修改对象的
可观察状态;mutable 成员被明确排除在这个承诺之外,所以缓存可以在
const 方法里更新。没有 mutable 时,cache_[key] = value 才会编译失败。
两点注意:
mutable用于逻辑 const(缓存、记忆化、统计埋点),不是用来掩盖一个 本来就该是非 const 的方法。const成员函数不会自动线程安全。如果两个线程同时对同一个Cache调用get,这个 mutable map 仍然是共享状态,仍然需要同步。
相关规则是 [dcl.type.cv](cv 限定对象)和 [expr.prim.this](const
成员函数里的 this)。常见误解“在 const 方法里写入一定是 UB”是错的;
编译器根据成员的 mutable 声明判断。
3. const_cast 只能移除原本非 const 对象的 const¶
int value = 42;
const int& view = value;
int* p = const_cast<int*>(&view);
*p = 100; // legal: the original object is non-const
const int constant = 42;
int* q = const_cast<int*>(&constant);
*q = 100; // undefined behavior
const_cast 改变的是表达式的类型,不是底层对象的 const 属性。修改一个
定义为 const 的对象在 [dcl.type.cv] 下是未定义行为。把原本非 const
对象的 const 视图转回非 const 是合法的;cast 本身受 [expr.const.cast]
约束。
这也是为什么 API 常常接收 const T&,却通过一个单独命名的方法返回可写
视图。类型系统在告诉你哪些对象可以安全修改;不要用 const_cast 把这些
信息静音。
应该怎么做¶
- 只读参数和返回值优先用
const T&,前提是不转移所有权。 - 让拥有者比指针或 view 活得更久。
string_view、span和裸指针都是 非拥有类型。 mutable只用于逻辑 const,并写清楚这块可变状态的同步要求。const_cast只用于已知原本非 const 的对象,最好收窄在一个 API 边界, 并写注释说明原因。- 不要以为
-Wcast-qual能抓住所有不安全转换;它只覆盖部分语法情况, 抓不住生命周期和“对象最初是否 const”的错误。
审查清单¶
- 引用是直接绑定临时对象,还是指针/view 只是指向它?
const方法是否修改了mutable成员?如果会,并发访问是否同步?const_cast移除的是否是原本非 const 对象的 const?- 每次使用指针、view 或引用时,拥有者是否还活着?