条款3:尽量使用const

const指针和函数声明

const修饰指针

char greeting[] = "Hello";
char* p = greeting; 	// non-const 指针,
                      // non-const 数据
const char* p = greeting; 	// non-const 指针,
                            	// const 数据
char* const p = greeting; // const 指针,
                          // non-const 数据
const char* const p = greeting; // const 指针,
                                // const 数据

 如果const出现在左侧:指向的是常量,const出现在右侧:指针本身是常量。

const修饰函数

void f1(const Widget* pw); // f1接受一个指向常量Widget对象的指针
void f2(Widget const* pw); // f2也一样

 const出现在类型的左边,或右边是等效的。

const修饰容器

std::vector<int> vec;
//...

// iter 的行为像 T* const
const std::vector<int>::iterator iter = vec.begin();
*iter = 10; 	// 可以修改指向的数据
++iter; 	// 错误! iter 本身是 const
//cIter 的行为像 const T*
std::vector<int>::const_iterator cIter =vec.begin();
*cIter = 10; 	// 错误! *cIter 是 const
++cIter; 	// 正确, 可以修改迭代器本身

const应用在函数中

 令函数返回一个常量值,往往可以降低因客户错误而造成的意外,下面是一个有理数的例子。

class Rational {
     }; // 有理数! 
const Rational operator*(const Rational& lhs, const Rational& rhs);

如果不小心把=写成了==

Rational a, b, c;
(a * b) = c; 	// 对a*b的结果调用operator=
if (a* b = c)  // 糟糕, 写错了,应该是 ==

 但这时候,由于我们返回的是一个const类型的,所以该做法在编译的时候就会提示错误,这也能让我们更快的找到错误。

const限定成员函数

在成员函数上使用const:
1、使类的接口意图更明确。知道哪些函数可以修改一个对象,哪些不能,这很重要。
2、使得使用const对象成为可能。
 C++的一个重要特性:仅在常量上不同的成员函数可以被重载。考虑表示文本块的类:

class TextBlock {
   
public:
    TextBlock(std::string str) {
   
        text = str;
    }
    const char& operator[](std::size_t position) const // const对象的operator[]
    {
   
        return text[position];
    } 
    char& operator[](std::size_t position) // non-const对象的operator[]
    {
   
        return text[position];
    } 
private:
    std::string text;
};


void print(const TextBlock& ctb) // 在这个函数中,ctb是const
{
   
    std::cout << ctb[0]; // 调用const的TextBlock::operator[]
}
 //TextBlock的运算符[]可以这样使用:
TextBlock tb("Hello");
 std::cout << tb[0]; // 调用non-const的TextBlock::operator[]
     
const TextBlock ctb("World");
std::cout << ctb[0]; // 调用const的TextBlock::operator[]

print(tb);   // 调用const的TextBlock::operator[]
print(ctb);  // 调用const的TextBlock::operator[]

tb[0] = 'x'; //正确
ctb[0] = 'x'; //错误

避免const重载的代码重复

 假设TextBlock中的[]运算符不仅返回对适当字符的引用,还执行边界检查,记录访问信息,甚至可能进行数据完整性验证。

class TextBlock {
   
public:
    ...
    const char& operator[](std::size_t position) const{
   
            ... // do bounds checking
            ... // log access data
            ... // verify data integrity
            return text[position];
    }
    char& operator[](std::size_t position) {
   
            ... // do bounds checking
            ... // log access data
            ... // verify data integrity
            return text[position];
    }
private:
    std::string text;
};

这边我们定义了一个const版本和一个非const版本的函数。
替代方案:让operator[]的一个版本调用另一个版本。先写const版本,然后脱离const限制。

class TextBlock {
   
public:
    ...
    const char& operator[](std::size_t position) const{
   // 和前面一样
            ...
            ...
            ...
            return text[position];
    }
    char& operator[](std::size_t position){
   //只需要调用const版本
            return const_cast<char&>( //对op[]的返回类型抛弃const;
	    //给*this的类型添加const;调用op的const版本[]
            static_cast<const TextBlock&>(*this)[position] 
        );
    }
    ...
};

1、在这种情况下,去掉返回值上的const是安全的,因为调用非const操作符[]的人首先必须有一个非const对象。
2、让非const操作符[]调用const版本是避免代码重复的安全方法。

总结

  • 声明const可以借助编译器检测使用错误。const可以应用于任何作用域的对象、函数参数和返回类型,以及作为一个整体的成员函数。
  • 编译器强制执行位常量,但你应该使用逻辑常量进行编程。
  • 当const和非const成员函数具有本质上相同的实现时,可以通过让非const版本调用const版本来避免代码重复。

相关推荐

  1. 3尽量使const

    2023-12-17 16:14:02       36 阅读
  2. 27:尽量少做转型动作

    2023-12-17 16:14:02       29 阅读
  3. C++中为什么尽量使using 代替 typedef

    2023-12-17 16:14:02       8 阅读
  4. 13:对象管理资源(智能指针)

    2023-12-17 16:14:02       22 阅读
  5. 【100sqlite3命令】

    2023-12-17 16:14:02       36 阅读
  6. 《Effective C++》33

    2023-12-17 16:14:02       46 阅读
  7. 《Effective C++》37

    2023-12-17 16:14:02       36 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-17 16:14:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-17 16:14:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-17 16:14:02       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-17 16:14:02       20 阅读

热门阅读

  1. Unity触摸 射线穿透UI解决

    2023-12-17 16:14:02       40 阅读
  2. 5.2 C++11堆内存管理:智能指针与垃圾回收

    2023-12-17 16:14:02       43 阅读
  3. SSRF漏洞:原理、示例和防范方法

    2023-12-17 16:14:02       40 阅读
  4. C++代码风格指南--Google(未完待续)

    2023-12-17 16:14:02       33 阅读
  5. Python 钉钉自动打卡脚本

    2023-12-17 16:14:02       58 阅读
  6. 深度学习代码片段收集

    2023-12-17 16:14:02       40 阅读
  7. C语言之枚举类型

    2023-12-17 16:14:02       39 阅读
  8. cisco packet tracer 路由器之间连线

    2023-12-17 16:14:02       30 阅读
  9. python单例模式

    2023-12-17 16:14:02       36 阅读
  10. 【面试】在Python中如何实现单例模式

    2023-12-17 16:14:02       28 阅读
  11. 多线程中的单例模式

    2023-12-17 16:14:02       42 阅读
  12. MySQL之锁

    2023-12-17 16:14:02       32 阅读