|
-
April 7th, 2006, 03:57 AM
#1
[RESOLVED] Mutable variable
When we declare the variable as mutable; it says that we want to change the value of that variable in middle of the program. So what it signifies rather if we declare a simple any variable then it also can be modify in the program\
Dose it having any spacial meaning?
-
April 7th, 2006, 04:05 AM
#2
Re: Mutable variable
Hmm, are you mixing mutable with the volatile keyword?
A mutable variable is a variable that can be modified from a constant member function:
Code:
class yourClass
{
protected:
mutable int a;
public:
void func() const
{
a++; // function is const, but we can modify this->a
}
};
- petter
Last edited by wildfrog; April 7th, 2006 at 04:20 AM.
Reason: in red
-
April 7th, 2006, 04:17 AM
#3
Re: Mutable variable
Got it.......
A variable can not be modified using the cosnt member function but mutable varibale can be changed using the const member function.
Thanks WildFrog
-
April 7th, 2006, 09:59 AM
#4
Re: Mutable variable
 Originally Posted by sapatchay
Got it.......
A variable can not be modified using the cosnt member function but mutable varibale can be changed using the const member function.
Thanks WildFrog
Yep. But don't let that tempt you into doing bad things. Consider that a const member function is promising that it will not change the observable state of the object. That is, a user of your class should be confident that - as far as he is concerned - calling the function leaves the object unchanged. So, mutable is useful in situations where you have some "housekeeping" data that doesn't affect the observable state of the object, but which may need to be modified in a const function.
One example of this may be that (for unexplained reasons) you want to count how often the function is called: this is irrelevant to your users, and does not affect them, so making the count a mutable member is quite permissable.
What is definitely not OK, though, is to use it to get around a const function because your design is poor, for example.
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|