-
volatile pointers
I was perusing Danny's article (http://www.informit.com/guides/conte...lus&seqNum=345) and was reminded of a question.
I've always used volatile in the context of a pointer: what the pointer points to changes due to other threads. We use something like:
volatile int* ptr=...;
In this case, the value in "ptr" is *not* volatile, rather, the value pointed to by the value in ptr.
One might have a need for:
volatile int my_int;
In which case the value in my_int needs to be volatile.
My confusion is this: how does the compiler know to not optimize *ptr in one case an my_int in another?
Question number two. Would this work:
volatile int& alias_ptr(*ptr);
And the reference be correctly handled?
Thanks
-
The compiler knows to disable *access optimization through the specific pointer*, not necessarily de-optimize the object itself. Consider a similar example with adding const implicitly:
Code:
void func (const string& s);
The string here is treated as const, but it doesn't have to be a true const string:
Code:
string mys;
func(mys) //const qualifier implicitly added to string
In your example, when the pointer is declare as pointing to a volatile int, any access through that pointer will not be optimized but when you access the int directly, its value might be optimized by storing a copy thereof in a CPU register.
As for:
Code:
volatile int& alias_ptr(*ptr);
You have a reference to a volatile int here. This means that every time you access that int through the reference variable alias_ptr, the int will be treated as a volatile variable. Of course, that doesn't mean that the bound variable becomes volatile. If you access *ptr directly, it might be optimized, so it all boils down to what you want to achieve: treat *ptr as volatile only when accessed via the reference or treat it as volatile all the time.
Last edited by Danny; 05-14-2009 at 05:22 PM.
Danny Kalev
Similar Threads
-
Replies: 4
Last Post: 06-02-2008, 07:30 AM
-
Replies: 12
Last Post: 01-02-2007, 12:41 PM
-
By premartha in forum .NET
Replies: 0
Last Post: 09-25-2006, 01:58 AM
-
By Benzsoft in forum VB Classic
Replies: 1
Last Post: 02-21-2002, 11:47 AM
-
Replies: 4
Last Post: 01-31-2001, 05:47 PM
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
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|