代码之家  ›  专栏  ›  技术社区  ›  Astor

如何访问const volatile std::array?

  •  0
  • Astor  · 技术社区  · 7 年前

    对于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?

    2 回复  |  直到 7 年前
        1
  •  4
  •   Martin Bonner supports Monica    7 年前

    你没有。

    std::array 有两个 operator [](size_t) . 一个给 *this 是常量,如果 *这个 *这个

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

    n4296

    我非常肯定,在所有版本的标准中都存在类似的语言。


    volatile std::atomic std::mutex 去做那件事。Volatile对微处理器地址空间中的特殊寄存器建模很有用。

        2
  •  4
  •   molbdnilo    7 年前

    const volatile int v[2] int s、 不是两个常量volatile数组 内景

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

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