谈谈 const
当成员函数的 const 和 no-const 版本同时存在, const object 只会(只能)调用 const 版本, non-const object 只会(只能)调用 non-const 版本
是否可被调用 | const object (data members 不得变动) | non-const object (data members 可变动) |
---|---|---|
const member functions (保障不更改data members) | √ | √ |
non-const member functions (不保障 data members 不变) | × | √ |
const String str("hello word");str.printf();如果当初设计 String::printf() 时未指明 const, 那么以上代码将是经由 const object 调用 non-const member function, 编译时会报错(并非咱们所愿)
class template std::basic_string<...> 有如下两个 member funcions
charT operator[](size_type pos) const{ ... /* 不用思考 COW */ }reference operation[](size_type pos){ ... /* 必须思考 COW */ }
COW: Copy On Write (援用技术数据共享机制)