devxlogo

A Mutable Object Member

A Mutable Object Member

When a data member is declared mutable, then it is legal to assign a value to it from a const member function. The following example may demonstrate when it is needed:

 class Buffer {	void * data;  //raw data buffer to be transmitted on the net	size_t size;  //size of  the data 	mutable int crc; //used to verify that no errors occurred during transmission;//a mutable variable is allowed to be modified from a const //member function. 	public:	//...	int GetCrc() const;	void Transmit() const; //copmutation of crc_val should be done here};void f() {Buffer buffer;//...fill buffer with databuffer.Transmit(); //crc can be modified here; other members may not}

Class buffer uses a data buffer transmitted via communication link after it has been filled. The filling process is quite slow and repetitive, so there’s no point in calculating the value of crc every time a few bytes are appended to data. On the other hand, the receiving size has to get the right crc of the data in order to ensure that no corruption has occurred along the way. Naturally, the computation of crc has to be done in Transmit(), right before sending buffer. Since Transmit()is declared as a const member function for obvious reasons, the data is not to be changed when transmitted. In order to allow assignment of the correct value to crc right on time, the crc member is defined mutable, and hence, can be modified even by a const member function such as Transmit().

See also  11 Effective Keyword Research Tools and Techniques
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist