【发布时间】:2018-08-31 13:18:06
【问题描述】:
我正在尝试创建一个 volatile 数组,我需要使用运算符 [] 访问它。
我找不到对 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?
【问题讨论】:
-
只是出于好奇:为什么需要一个 volatile 数组开始?
-
@BaummitAugen 我正在编写一个代码,该代码需要在编译时使用 std::array 计算一些复杂的东西并调查生成的程序集。我使用 volatile 强制编译器创建 std::array ,即使我不对其执行任何操作。