C ++ and object-oriented in the mutable const

C ++ and object-oriented in the mutable const

In this paper, I record for object-oriented const (constant) and mutable (variable) understood

const

  1. const member functions is applied to the back (and specified in the declaration and definition)

The idea is to tell the compiler that this function does not modify the contents of the members of the class of the class object. Take a look at the code:

int sum(const Test &t){
	int start = t.beg_pos();
	int len = t.length();
	int res = 0;
	for(int i=0;i<len;++i){
		res += t.elem(start+i);
	}
	return res;
}

Code class t is const reference parameters, so we must ensure that t will not be modified when calling a function of t. But calling the function, the compiler does not know which function will modify the contents of t. Therefore, it must decide whether to raise const, to tell the compiler whether this function will change the contents of the object after the function.
(Although the compiler does not analyze each function it is const or non-const, but declared as const function, it will check if any content modify the object)

  1. According to a member function may be overloaded or not const

Below this category, we offer a version const and non-const version val function.
Non-const object will call the non-const version (changing the contents of the object it does not matter), and will call the const object const version.

class Test{
public:
	Test(const MyTest& val)
		:_val(val){}
	const Test& val()const{ return _val};
	Test& val(){ return _val};
private:
	MyTest _val;
};

mutable

In const object, we do not want to modify the contents of the object. But in some classes which we have to do a similar traversed by modifying certain variables operation, but this time will conflict with const. This is what we can add in front of mutable variables, to tell the compiler to modify this variable does not destroy the object of constant sex.

Published 51 original articles · won praise 6 · views 6298

Guess you like

Origin blog.csdn.net/weixin_40859716/article/details/104383016