如何访问常量易失性 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 ;
}

工作得很好。

如何访问常量易失性 std::array?

你没有。

std::array有两个重载operator [](size_t)。一个表示*this是常量,一个如果*this是非常量。 这些都不适合你 - 因为*this是常量不稳定的。

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

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

如果尝试通过使用具有非可变限定类型的 glvalue 来引用用可变限定类型定义的对象,则程序行为是未定义的"。

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


如果您使用volatile来支持多线程 - 请不要这样做。 它实际上没有帮助。 您需要使用std::atomicstd::mutex来执行此操作。 易失性可用于对微处理器地址空间中的特殊寄存器进行建模。

>const volatile int v[2]是一个包含两个常量易失性int的数组,而不是一个由两个ints组成的常量易失性数组。

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

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

最新更新