c++ - mdspan 和严格的别名规则

标签 c++ undefined-behavior strict-aliasing

如果我没记错的话,由于严格的别名规则,通过指针算术访问多维数组的第二行是未定义的行为。

有一个提案,名为 mdspan ,据我了解,它旨在提供多维数组 View 。如何在不违反严格别名规则的情况下实现这样的类?

解决方法可能是将数据reinterpret_cast来回转换为char *。不过,我看了一下this reference implementation我没有看到这样的事情。

这是引用实现的摘录:

template < typename DataType , class ... Properties >
class mdspan
{
public:
  // ...
  using element_type = DataType ;
  using pointer      = element_type * ;
  using reference    = element_type & ;

private:
  pointer  m_ptr ;
  mapping  m_map ;

public:
  // ...

  template < class ... IndexType >
  explicit constexpr mdspan
    ( pointer ptr , IndexType ... DynamicExtents ) noexcept
    : m_ptr(ptr), m_map( DynamicExtents... ) {}


  // ...

  template< class ... IndexType >
  constexpr reference
  operator()( IndexType ... indices) const noexcept
    { return m_ptr[ m_map( indices... ) ]; }
};

最佳答案

我意识到我误解了整件事。该提案明确指出:

The proposed polymorphic multidimensional array reference (mdspan) defines types and functions for mapping indices from a multidimensional index space (the domain) to members of a contiguous span of objects (the codomain).

因此,它被设计为一维数组的多维 View ,不存在别名问题。

我在其他地方读到它的目的是替换像 f(double [][5],int) 这样的代码,这让我很困惑。

关于c++ - mdspan 和严格的别名规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49665881/

相关文章:

c++ - 我怎样才能在同一行得到我程序的所有总和?

c - 对 char 数组结构成员进行类型双关

c++ - 在 C++ 中使用 `restrict` 类型限定符和 `unique_ptr` 的受限别名

c - 为什么这些构造使用增量前和增量后未定义的行为?

c++ - IEEE-754 浮点计算、相等和缩小

c++ - 类型别名和动态分配的数组

C++ typedef 静态函数指针 : undefined symbol

c++ - 会在不同编译器中持续触发的警告?

c++ - 将参数传递给方法时内联初始化整数数组

c++ - 超出 C++ 的界限和未定义的行为