multi_array_view没有深拷贝的作业

multi_array_view assignment without deep copy?

本文关键字:深拷贝 作业 array view multi      更新时间:2023-10-16

如何重新分配提升multi_array_view以指向multi_array的不同部分?我不想要深拷贝。

boost::multi_array<int, 2> a(...);
array_view b = a[indices[index_range(0, 5)][index_range()]];
array_view c = a[indices[index_range(0, 10)][index_range()]];
b = c; // don't work

升压源:

template <typename ConstMultiArray>
multi_array_ref& operator=(const ConstMultiArray& other) {
    function_requires< 
      multi_array_concepts::
      ConstMultiArrayConcept<ConstMultiArray,NumDims> >();
    // make sure the dimensions agree
    BOOST_ASSERT(other.num_dimensions() == this->num_dimensions());
    BOOST_ASSERT(std::equal(other.shape(),other.shape()+this->num_dimensions(),
                            this->shape()));
    // iterator-based copy
    std::copy(other.begin(),other.end(),this->begin());
    return *this;
}

更新:我最终更改了程序中的方法,以保留对boost::indices[...]创建的索引对象的引用。然后,我可以随时使用该对象创建新array_view

看起来multi_array_ref模型与C++参考非常接近:

  • 不可重新拔插
  • 它在语义上是它"绑定到"的对象的别名

然而,有点令人惊讶的是,const_multi_array_ref的情况似乎并非如此。请注意这些文档引用:

  • 构造函数和赋值

此库中的所有非常量数组类型都提供赋值运算符运算符 operator=()。每个数组类型 multi_array、multi_array_ref、子数组和array_view都可以从任何其他数组类型分配,只要它们的形状匹配即可。const 变体、const_multi_array_ref、const_subarray 和 const_array_view 可以是具有匹配形状的数组的副本的源。赋值会导致数组中包含的数据的深层(逐个元素)副本

这讨论了分配给可变数组(视图)。

然而:

  • const_multi_array_ref(const const_multi_array_ref& x);

影响。这将构造 x 的浅拷贝

方法

也许你可以改用const_multi_array_ref

否则,您可能应该寻求"打破"不可重新拔插引用的绑定,就像我们对C++引用所做的那样:std::reference_wrapper<>或类似的间接。