我正在处理对volatile
引用对象的现有C ++代码
volatile vClass & vobj;
我来自C
所以当我用来访问内存映射的IO时,我熟悉volatile
:
*((volatile unsigned int *) 0x12345678) = 0x5
问题
将volatile
应用于(引用)对象有什么影响?
我猜它的所有数据成员都继承volatile
但是如果成员函数具有非易失性内存访问(如
void vClass::AccessMem() {*((unsigned int *) 0x12345678) = 0x5;}
内存访问是否会变得不稳定?
答案 0 :(得分:2)
成员函数必须是volatile才能从volatile对象调用:
int not_a_member;
struct vClass {
int i;
void set(int j) {
i=j; //i is not accessed as a volatile
static_assert(std::is_same_v<decltype((i)),int&>);
}
void set_v(int j) volatile{
i=j; //here i is accessed as a volatile
static_assert(std::is_same_v<decltype((i)),volatile int&>);
not_a_member=j;//here not a volatile access because "not_a_member" is
// not a member.
//To understand what happen, since you are a C programmer it is going to be simple.
//The volatile qualifier is actualy apply to the "this" pointer,
// which is a pointer to the object from which this member function is
// called. So inside this function "this" as the type "volatile vClass"
//Inside a member function, all access to member data, as "i" are
//actualy short ends for "this->i". So in this access, "i"
//adopt the volatile qualifier of "this".
//So the volatile qualifier just applies to the data member of the object.
}
}
void use_vClass(){
volatile vClass x;
x.set(10); //Do not compile: "Error:try to access volatile object as non volatile"
x.set_v(10); //Compile
}
因此,从volatile对象或引用开始,您只需调用volatile限定成员函数,所有数据成员访问都将是“volatile”。
答案 1 :(得分:1)
它是对易失性而非易变性引用的引用(后者无论如何都没有意义)。
它类似于:
volatile char * ptr = ...;
ptr的内存可以在没有通知的情况下改变,但是ptr本身是稳定的(不像它是
)char * volatile ptr = ...;