C++ mutable 的用法

代码编译运行环境:VS2017+Win32+Debug


mutalbe 的中文意思是“可变的,易变的”,是constant(即C++中的const)的反义词。在C++中,mutable也是为了突破const的限制而设置的,被mutable修饰的变量将永远处于可变的状态。

mutable的作用有两点:
(1)保持常量对象中大部分数据成员仍然是“只读”的情况下,实现对个别数据成员的修改;
(2)使类的const函数可以修改对象的mutable数据成员。

使用mutable的注意事项:
(1)mutable只能作用于类的非静态和非常量数据成员。
(2)在一个类中,应尽量或者不用mutable,大量使用mutable表示程序设计存在缺陷。

示例代码如下:

#include <iostream>
using namespace std;

//mutable int test;//编译出错

class Student
{
	string name;
	mutable int getNum;
	//mutable const int test;    //编译出错
	//mutable static int static1;//编译出错
	
public:
	Student(char* name)
	{
		this->name=name;
		getNum=0;
	}
	string getName() const
	{
		++getNum;
		return name;
	}
	void pintTimes() const
	{
		cout<<getNum<<endl;
	}
};

int main(int argc, char* argv[])
{
	const Student s("张三");
	cout<<s.getName().c_str()<<endl;
	s.pintTimes();
	return 0;
}

程序输出结果:

张三
1

mutable不能修饰const数据成员容易理解,因为mutable与const本是反义,同时修饰不是自相矛盾吗。mutable不能修饰static数据成员,因为static数据成员存储在Data段或BSS段,属于类,不属于类对象,那么常对象和常函数可以对其任意地修改,所以类的static数据成员根本不需要mutable的修饰,但对于常对象的数据成员则不可以被修改,若想修改,则需要mutable的修饰。示例代码如下:

#include <iostream>
using namespace std;

class Student
{
	string name;

public:
	static int test1;
	void modify() const
	{
		test1=15;
		cout<<test1<<endl;
	}
};

int Student::test1;//申明test1并按照编译器默认的值进行初始化
int main(int argc, char* argv[])
{
	const Student s("张三");
	s.test1=5;//常对象可以修改静态类的数据成员test1
	cout<<Student::test1<<endl;
	s. modify();//常函数修改
	return 0;
}

程序输出结果是:

5
15

参考文献

[1] C++高级进阶教程.陈刚.武汉大学出版社.1.5mutable的用法.P12-P14

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值