如何访问 const volatile std::array?

How do I access a const volatile std::array?

我正在尝试创建一个可变数组,我需要使用运算符 [] 访问它。

我找不到为 std::array 执行此操作的方法,但是内置数组工作正常。

使用 GCC 8.2.0 后:

#include <iostream>
#include <array>
int main()
{
    const volatile std::array<int,2> v = {1,2};
    std::cout << v[0] << std::endl ;
}

给予

<source>: In function 'int main()':

<source>:6:21: error: passing 'const volatile std::array<int, 2>' as
'this' argument discards qualifiers [-fpermissive]

 std::cout << v[0] << std::endl ;

                 ^

In file included from <source>:2:

/opt/compiler-explorer/gcc-8.2.0/include/c++/8.2.0/array:185:7: note:
in call to 'constexpr std::array<_Tp, _Nm>::value_type& std::array<_Tp, 
_Nm>::operator[](std::array<_Tp, _Nm>::size_type) [with _Tp = int; long 
unsigned int _Nm = 2; std::array<_Tp, _Nm>::reference = int&; 
std::array<_Tp, _Nm>::value_type = int; std::array<_Tp, _Nm>::size_type = 
long unsigned int]'

   operator[](size_type __n) noexcept

   ^~~~~~~~

Compiler returned: 1

#include <iostream>
int main()
{
    const volatile int v[2] = {1,2};
    std::cout << v[0] << std::endl ;
}

工作得很好。

如何访问 const volatile std::array?

你不知道。

std::array 有两个重载 operator [](size_t)。一个用于 *this 的是常量,一个用于 *this 的是非常量。这些都不适合你 - 因为 *this 是 const volatile.

如果您使用 const_cast 删除 volatile 限定符,结果可能会编译,甚至可能看起来有效。然而,实际结果是未定义的行为(因为底层对象实际上 volatile);这意味着当你来给客户做重要的演示时它会停止工作。

致语言律师:n4296 是 C++14 之前的最后一份标准委员会草案。第 7.1.6.1 节 [dcl.type.cv] 第 6 段说:

If an attempt is made to refer to an object defined with a volatile-qualified type through the use of a glvalue with a non-volatile-qualified type, the program behavior is undefined".

我很确定标准的所有版本中都存在类似的语言。


如果您使用 volatile 来支持多线程 - 请不要。它实际上并没有帮助。您需要使用 std::atomicstd::mutex 来做到这一点。 Volatile 对于微处理器地址 space.

中的特殊寄存器建模很有用

const volatile int v[2] 是两个 const volatile int 的数组,而不是两个 ints.

的 const volatile 数组

使用类似的std::array编译:

int main()
{
    std::array<const volatile int, 2> w = {1,2};
    std::cout << w[0] << std::endl ;
}