Advanced C++ -- Logic Constness and Bitwise Constness
来源:互联网 发布:免安装java 编辑:程序博客网 时间:2024/05/29 13:50
首先介绍一下什么是Logic Constness和Bitwise Constness,Logic Constness指的是function 后的const修饰,我们只知道这个function被const修饰了,但是并没有任何变量被const,Bitwise Constness指的是变量(指针,或者引用等,基本上任何的二进制储存值)被const修饰,那么我们下面就用例子来进行探索。
#include<iostream>#include<vector>#include<string>using namespace std;class BigArray{ vector<int> v; int accessCounter; int *v2;public: int getItem(int index) const{ //accessCounter++; const_cast<BigArray*>(this)->accessCounter++; return v[index]; } void setV2Item(int index, int x){ *(v2+index) = x; } // Quiz: const int* const fun(const int* const& p) const{ //return accessCounter++; }};int main(){ BigArray b;}
首先我们看getItem函数,因为这个函数不对对象的数据进行任何修改,所以我们将其修饰为const,一开始我们注释掉前两句,只有return v[index]; 发现程序编译通过,因为没有任何修改实例变量的操作,但是如果我们注释掉第一行,也就是accessCounter++; 我们就会发现,程序编译报错了,报错的原因就是getItem是Logic Const的函数,所以里面不能够对变量进行修改,因为这样就是打破了Bitwise Constness,但是是不是我们就不能对accessCounter进行修改呢?其实并不是,大致有两种方法可以对其进行修改:
- 使用mutable,在变量前面使用mutable进行修饰,这样就可以在const修饰的函数中进行修改。
- 还有一种C++方式,但是并不推荐的就是,使用const_cast对变量的const属性进行cast,这样就可以进行修改而不报错,但是此方法还是不推荐的,实际上在实际开发中,const修饰function的目的就是控制其不能修改变量值。
再解答一下Quiz的一长串const修饰到底意味着什么:
- func的返回值为const的int值,其值为const,指针也为const,表示value和pointer都不可更改
- func的参数是一个指向const integer的const指针的引用
- func也是一个const function,说明不能直接对类中的变量进行修改,并且只能调用其他const函数
0 0
- Advanced C++ -- Logic Constness and Bitwise Constness
- bitwise constness与logical constness的区别
- bitwise constness与logical constness【EC++笔记】
- Bitwise operation and usage
- LeetCode[Bitwise]----Bitwise AND of Numbers Range
- Chapter 1. General Unix and Advanced C
- 读Advanced C and C++ Compiling
- Inna and Binary Logic
- memberwise and bitwise in C++
- Bit shifting and bitwise operations
- Bitwise AND of Numbers Range
- Bitwise AND of Numbers Range
- Bitwise AND of Numbers Range
- Bitwise AND of Numbers Range
- Bitwise AND of Numbers Range
- Bitwise AND of Numbers Range
- Bitwise AND of Numbers Range
- Bitwise AND of Numbers Range
- leetcode--remove_duplicates_from_sorted_list
- java 枚举使用
- GitHub for windows离线安装
- C++文件读写
- WinRAR 5.1-5.3 64位注册方法,rarreg.key
- Advanced C++ -- Logic Constness and Bitwise Constness
- PCB新手使用中要注意的问题
- xcode8类似于VVDocument的快速注释
- oracle(除数不能为0)
- 使用Erlang UDP做仿真通信
- 图片上传、图片转化成base64字符串上传
- 汇编语言程序设计
- lightoj1414-容斥原理
- 如何自己编写Makefile(入门级)