Lets say I have an object with an integer instance variables and 1 member function. The function runs on a separate thread, and consistently updates the value of the instance variable. I have a second function (part of a different class) that also runs on a separate thread, and needs real time access to the integer instance variable in the first object. Therefore, I pass in a pointer to the instance variable to the second function and the second function just dereferences the pointer. This way the second function always has access to the updated value of the instance variable.
However, I do not want the second function to be able to change the value of the instance variable. I want it to have read-only access, but since I am passing in a pointer to the instance variable, will it be able to change the value of the instance variable? If so, how do I restrict pointer dereferencing to read only? If this isn’t possible, what would be the safest solution to this problem?
Mac OS X Snowleopard, Xcode 3.2.6. Objective-C with Cocoa.
EDIT: Sorry I forgot to mention that I can’t make the instance variable constant, because I need the class it belongs to to be able to modify it. If I make it constant, it would completely restricting writing to the variable.
You can use the type system here. Instead of having something like
int*you can haveconst int *, which means it’s a pointer to a constant int. It’s possible to get around this by casting back to(int *)inside the function, but this is a violation of the type system (hence the explicit cast) and well-behaved functions won’t do that.Note, you may also need to throw in
volatileif your function needs to make sure it has the up-to-date value. Otherwise the compiler may decide it’s ok to cache the results of the dereference somewhere.