gpt4 book ai didi

C++ 对 volatile 对象的引用 - 原因和影响

转载 作者:行者123 更新时间:2023-11-30 02:21:25 24 4
gpt4 key购买 nike

我正在处理现有的 C++ 代码,这些代码具有对对象的 volatile 引用

volatile vClass & vobj;

我来自 C,所以我很熟悉 volatile 用来访问内存映射的 IO,如下所示:

*((volatile unsigned int *) 0x12345678) = 0x5

问题

volatile 应用于(对)对象的影响是什么?

我猜想它的所有数据成员都继承了 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 ”的。

关于C++ 对 volatile 对象的引用 - 原因和影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48346420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com