O
Ole Nielsby
I have objects that sometimes overwrite themselves by something else,
using placement new.
I will spare you for the details, but the objects serve as stack frames
and are placed contiguosly, and the overwriting happens when a frame
gets popped and something else gets pushed. This is a much simplified
version:
class Frame {...}
class Frame1 : Frame {...}
class Frame2 : Frame {
private:
int /*volatile?*/ f;
public:
void m() {
int ff = f;
new ((void*)this) Frame1(...);
doSomething(ff);
}
}
This seems to work so far. What bugs me is: could a smart
optimizer decide that f can't be modified because it is private
and no Frame2 methods modify it, and then postpone the
fetching until after the placement new? Is the volatile
keyword sufficient/required to prevent this? If I don't want
to make all such fields volatile (since this may prevent some
valid optimizations), can I achieve the same effect by:
int ff = *((int *volatile)&f);
or whatever the syntax? Or:
int volatile ff = f;
Or should I expose dummy methods that modify the fields?
class Frame2 ...{... void dummy(){f = 0;} ....}
using placement new.
I will spare you for the details, but the objects serve as stack frames
and are placed contiguosly, and the overwriting happens when a frame
gets popped and something else gets pushed. This is a much simplified
version:
class Frame {...}
class Frame1 : Frame {...}
class Frame2 : Frame {
private:
int /*volatile?*/ f;
public:
void m() {
int ff = f;
new ((void*)this) Frame1(...);
doSomething(ff);
}
}
This seems to work so far. What bugs me is: could a smart
optimizer decide that f can't be modified because it is private
and no Frame2 methods modify it, and then postpone the
fetching until after the placement new? Is the volatile
keyword sufficient/required to prevent this? If I don't want
to make all such fields volatile (since this may prevent some
valid optimizations), can I achieve the same effect by:
int ff = *((int *volatile)&f);
or whatever the syntax? Or:
int volatile ff = f;
Or should I expose dummy methods that modify the fields?
class Frame2 ...{... void dummy(){f = 0;} ....}