gpt4 book ai didi

c++ - 什么时候成员函数应该同时是 const 和 volatile?

转载 作者:可可西里 更新时间:2023-11-01 15:35:27 30 4
gpt4 key购买 nike

我在阅读有关 volatile 成员函数的内容时发现成员函数可以同时是 const 和 volatile 的断言。我没有真正使用过这样的东西。任何人都可以分享他们在将成员函数同时用作 const 和 volatile 的实际使用方面的经验。

我写了小类来测试同样的:

class Temp
{
public:

Temp(int x) : X(x)
{
}

int getX() const volatile
{
return X;
}

int getBiggerX()
{
return X + 10;
}
private:
int X;
};

void test( const volatile Temp& aTemp)
{
int x = aTemp.getX();
}

int main(int argc, char* argv[])
{
const volatile Temp aTemp(10);
test(aTemp);

return 0;
}

最佳答案

cv 资格提炼意味着:

I won't change the value, but there is something out there that can.

您向自己 promise 您不会更改该值(const 限定条件)并请求编译器将其粘糊糊的手从该对象上移开并关闭所有优化( >volatile 资格)。不幸的是,在公平对待 volatile 方面,编译器供应商之间几乎没有标准。 volatile 毕竟是对编译器的提示

一个实际用例是系统时钟。假设 0xDEADBEEF 是您要写入的硬件时钟寄存器的系统特定地址:

int const volatile *c = reinterpret_cast<int *>(0xDEADBEEF);

您无法修改该寄存器值,但每次读取它时,它很可能具有不同的值。

另外,可以用它来建模 UARTs .

关于c++ - 什么时候成员函数应该同时是 const 和 volatile?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/655027/

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