gpt4 book ai didi

c++ - 为什么对 volatile int 的 const 引用需要 static_cast?

转载 作者:太空狗 更新时间:2023-10-29 19:52:45 24 4
gpt4 key购买 nike

给定以下代码:

struct Foo { 
volatile int i;
};

const int& bar = foo.i;

我得到:

error: invalid initialization of reference of type 'const int&' from expression of type 'volatile int'

除非我提供 static_cast<volatile int> .

最佳答案

C++ 中类型的“易变性”与“常量”的工作方式几乎完全相同——也就是说,一个对象是 volatile不能分配给非 volatile引用,以同样的方式

const int i = 3;
int& j = i; // won't work

类似地,只有标记为 volatile 的方法可以在 volatile 对象上调用:

struct S
{
void do_something() volatile {}
void do_something_else() {}
};

volatile S s;
s.do_something(); // fine
s.do_something_else(); // won't work

方法可以被“波动性”重载,就像它们可以被 const-ness 重载一样。

在 C++ 标准语中,这些东西被称为 cv-qualifiers,以强调它们以完全相同的方式工作。 (C99 添加了第三个以相同方式工作的 restrict ,在某些 C++ 编译器中可作为扩展使用)。您可以使用 const_cast<> 更改 cv 限定符-- 越强大static_cast<>不需要。

编辑:

需要说明的是,一个类型可以同时拥有 constvolatile同时修饰符,一共给出了四种可能:

int i;
const int j;
volatile int k;
const volatile int l;

关于c++ - 为什么对 volatile int 的 const 引用需要 static_cast?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20672660/

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