![](/img/trans.png)
[英]Calling volatile member function using not volatile object in C++
[英]C++ reference to volatile object - reasons and effects
我正在研究具有对象的volatile
引用的现有C ++代码
volatile vClass & vobj;
我来自C
所以我熟悉volatile
用于访问内存映射的IO,如下所示:
*((volatile unsigned int *) 0x12345678) = 0x5
题
将volatile
应用于(引用)对象有什么影响?
我猜它的所有数据成员都继承了volatile
但是如果一个成员函数有非易失性内存访问,那该怎么办呢
void vClass::AccessMem() {*((unsigned int *) 0x12345678) = 0x5;}
内存访问是否会变得不稳定?
成员函数必须是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”。
它是对易失性而非易变性引用的引用(后者无论如何都没有意义)。
它类似于:
volatile char * ptr = ...;
ptr的内存可以在没有通知的情况下改变,但是ptr本身是稳定的(不像它是
char * volatile ptr = ...;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.