tags:

views:

104

answers:

3

In a multithreaded scenario, I have a method like this:

bool WaitForChange( time_duration WaitTime ) const;

This method waits either until the state of the object has changed and returns true, or until the timeout times out (how do you say that?) and returns false.

My intuition is, that const is to protect against unwanted side-effects of the method itself, so this is fine. But then again, some user might think that the state of the could not have changed, since the method is declared const. Is that user stupid, or should I make the method non-const in order to avoid confusion?

+4  A: 

I vote for constness.

The method itself does not change anything, just waits...

extropy
+10  A: 

By declaring the method as const, you say "Calling this method doesn't change the state of the object." This is (hopefully) true. So make it const.

If anybody thinks, const-ness means "While this method is called, no one else can change the object state" than that person is wrong.

Sebastian
A: 

If you're waiting to see if the object members have changed... what about volatile?

bool WaitForChange( time_duration WaitTime ) volatile

const implies the state of the object is the same throughout the function call, so I wouldn't use it. volatile, on the other hand, indicates to the compiler that the members should be re-fetched whenever they are accessed, which is probably what you want if you're looking for changes.

AshleysBrain
-1 You're confusing idiom with syntax. `const` guarantees that the function will not "modify the state of the object for which it is called." That, and nothing more. `volatile` is only needed when "an entity can have its value changed by extralinguistic means; for example, a real time clock." (Both quotes from Stroustrup, http://www2.research.att.com/~bs/glossary.html)
egrunin