如果我没记错的话,由于严格的别名规则,通过指针算术访问多维数组的第二行是未定义的行为。
有一个提案,名为 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/