const_cast与mutable
来源:互联网 发布:男生衣服搭配淘宝知乎 编辑:程序博客网 时间:2024/06/06 05:40
const_cast:用于修改类的const属性
1.作用:用于去除对象的const限定
2.用法:const_cast<type_id> (expression) //type_id必须是指针或者引用
3.注意:不是为了改变const变量的值(改变const的值的行为是未定义的),而是把const参数的引用或者指针传入->接收非const参数的指针和引用的函数中
例2,3中虽然,fun中改变test的值是可以通过编译的,但是其行为是未定义的!!!!!
所以修改const_cast时要确保函数没有改变变量.
举例:
- 例1:
- int fun(int a)
- {
- ...
- return a;
- }
- int main()
- {
- const int test=1;
- fun(test);//能通过编译,因为传递形参,test本身的值不可能变
- }
- 例2:
- int fun(int *a)
- {
- ...
- return *a;
- }
- int main()
- {
- const int test=1;
- fun(&test);//不能通过编译,因为传递const的地址,fun是可能改变test的值的
- fun(const_cast<int*> (&test));//可以通过编译,因为const_cast去除了对象test的const属性,允许使用test的指针到非const参数的函数中
- }
- 例3:
- int fun(int &a)
- {
- ...
- return a;
- }
- int main()
- {
- const int test=1;
- fun(test);//不能通过编译,传递const的引用,fun可能改变test的值
- fun(const_cast<int&> (test));//可以通过编译,去除了test的const属性,允许使用test的引用到非const参数的函数中
- }
mutable:
在类中,mutable修饰的变量,可以被const成员函数改变
0 0
- const_cast与mutable
- mutable与volatile
- const 与mutable
- mutable
- mutable
- mutable
- mutable
- mutable
- mutable
- mutable
- mutable
- mutable
- mutable
- mutable
- const_cast
- const_cast
- const_cast
- const_cast
- 【颗粒归仓】(四)代码走查---开篇
- 高价求苹果企业IOS enterprise开发者帐号
- 读书笔记---linux基本指令
- POJ-1258-Agri-Net(最小生成树 普利姆)
- 优化for循环效率
- const_cast与mutable
- 深度强化学习初探
- Three.js中的纹理Texture
- Ehcache实例
- MATLAB 神经网络基础(4)
- 最大公约数和最小公倍数问题
- Java中HashMap详解
- 微信摇红包H5应用开发技术分享及源代码(80万微信红包实战)
- POJ2389大数相乘