Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
May 12, 1998



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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. 
	int GetCrc() const;
	void Transmit() const; //copmutation of crc_val should be done here

void f() {
Buffer buffer;

//...fill buffer with data

buffer.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().
Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date