Effective C++ Item3
2015-09-06 14:25
253 查看
只要可能就用const
1.const 指针
T* const p p 是const *p非const p = p++ //ok *p = xx //error
const T* p p非const *p是const p = p++ //error *p=xx //ok
注意:这两种类型作为函数参数传递没有区别
2.const 成员函数
返回类型为const 引用或指针是给const对象调用
mutable修饰成员变量在const对象中允许被修改
class TextBlock
{
public:
...
const char& operator[](std::size_t position) const // same
as before
{
...
...
...
return text[position];
}
char& operator[](std::size_t position) //
now just calls const op[]
{
return
const_cast<char&>(
// cast away const on
// op[]'s return type;
static_cast<const TextBlock&>(*this)
// add const to *this's type;
[position] // call const version of op[]
);
}
...
};
· 将某些东西声明为 const 有助于编译器发现使用错误。const 能被用于任何 scope(范围)中的 object(对象),用于 function parameters(函数参数)和 return types(返回类型),用于整个 member functions(成员函数)。
· 编译器坚持 bitwise constness(二进制位常量性),但是你应该用 conceptual constness(概念上的常量性)来编程。(此处原文有误,conceptual constness为作者在本书第二版中对 logical constness 的称呼,正文中的称呼改了,此处却没有改。其实此处还是作者新加的部分,却使用了旧的术语,怪!——译者注)
·
9777
当 const 和 non-const member functions(成员函数)具有本质上相同的实现的时候,使用 non-const 版本调用 const 版本可以避免 code duplication(代码重复)
1.const 指针
T* const p p 是const *p非const p = p++ //ok *p = xx //error
const T* p p非const *p是const p = p++ //error *p=xx //ok
注意:这两种类型作为函数参数传递没有区别
2.const 成员函数
返回类型为const 引用或指针是给const对象调用
mutable修饰成员变量在const对象中允许被修改
class TextBlock
{
public:
...
const char& operator[](std::size_t position) const // same
as before
{
...
...
...
return text[position];
}
char& operator[](std::size_t position) //
now just calls const op[]
{
return
const_cast<char&>(
// cast away const on
// op[]'s return type;
static_cast<const TextBlock&>(*this)
// add const to *this's type;
[position] // call const version of op[]
);
}
...
};
· 将某些东西声明为 const 有助于编译器发现使用错误。const 能被用于任何 scope(范围)中的 object(对象),用于 function parameters(函数参数)和 return types(返回类型),用于整个 member functions(成员函数)。
· 编译器坚持 bitwise constness(二进制位常量性),但是你应该用 conceptual constness(概念上的常量性)来编程。(此处原文有误,conceptual constness为作者在本书第二版中对 logical constness 的称呼,正文中的称呼改了,此处却没有改。其实此处还是作者新加的部分,却使用了旧的术语,怪!——译者注)
·
9777
当 const 和 non-const member functions(成员函数)具有本质上相同的实现的时候,使用 non-const 版本调用 const 版本可以避免 code duplication(代码重复)
相关文章推荐
- C++面试题
- C++中tuple类型
- 【C++】继承时构造函数和析构函数
- Effective C++——条款25(第4章)
- C语言--enum,typedef enum 枚举类型详解
- 漫谈C指针第八讲---参数传递的三道题目
- C++/C, Java学习资料
- C++函数声明和定义深度解析(转)
- C++ 11 学习2:空指针(nullptr) 和 基于范围的for循环(Range-based for loops)
- C++中引用(&)的用法和应用实例
- C++11系列学习之二-----lambda表达式
- C++的第一步:Visual Studio 6.0~2013 各版本编译器下载汇总
- C/C++实现动态数组
- 指针与C++的基本原理
- Effective C++——条款24(第4章)
- C语言中send()函数和sendto()函数的使用方法
- C++中的多态性
- C++_运算符重载的注意事项
- C语言结构体中字符数组的问题
- C语言实现将字符串“askdaskaskdaskg”删除制定字符“ask”