Boost MultiArray复制构造函数
Boost MultiArray Copy Constructor
我在理解boost::multi_:array的复制构造函数实现时遇到了一个问题。
当我尝试以下
std::vector<double> a;
std::vector<double> b;
a.resize(12);
b.resize(10);
a=b;
一切顺利,
但当我尝试
boost::multi_array<double,1> a;
boost::multi_array<double,1> b;
a.resize(boost::extents[12]);
b.resize(boost::extents[10]);
a=b;
我崩溃了。
我期望同样的行为,但我也找不到任何有用的文档。
谁有主意?
对
awallrab
看起来boost::multi_array
在赋值方面就像std::valarray
一样,那就是两个数组的大小必须匹配。
根据文档:
每个数组类型
multi_array
,multi_array_ref
,subarray
和array_view
都可以从任何其他数组类型中分配,只要它们的形状匹配。
boost::multi_array赋值操作符的语义糟糕得令人恼火,它浪费了开发人员无数的时间来寻找像这样的答案,更糟糕的是,天知道在世界各地的项目中引入了多少未被发现的细微错误,其原因我可以最好地描述为可笑的傲慢。
可以这样修改multi_array.hpp中的赋值操作符:
// replacement for arrogant boost::multi_array assignment semantics
template <typename ConstMultiArray>
multi_array& operator=(const ConstMultiArray& other) {
// deallocate
deallocate_space();
base_ = 0;
allocated_elements_ = 0;
// copy members of const_multi_array_ref
storage_ = other.storage_;
extent_list_ = other.extent_list_;
stride_list_ = other.stride_list_;
index_base_list_ = other.index_base_list_;
origin_offset_ = other.origin_offset_;
directional_offset_ = other.directional_offset_;
num_elements_ = other.num_elements_;
// allocate
allocator_ = other.allocator_;
allocate_space();
// iterator-based copy
std::copy(other.begin(),other.end(),this->begin());
return *this;
}
multi_array& operator=(const multi_array& other) {
if (&other != this) {
// deallocate
deallocate_space();
base_ = 0;
allocated_elements_ = 0;
// copy members of const_multi_array_ref
storage_ = other.storage_;
extent_list_ = other.extent_list_;
stride_list_ = other.stride_list_;
index_base_list_ = other.index_base_list_;
origin_offset_ = other.origin_offset_;
directional_offset_ = other.directional_offset_;
num_elements_ = other.num_elements_;
// allocate
allocator_ = other.allocator_;
allocate_space();
// copy
boost::detail::multi_array::copy_n(other.base_,other.num_elements(),base_);
}
return *this;
}
在这种情况下,与boost作者的无关信念相反,这种修复不会破坏任何东西。它不会破坏任何东西的原因是,如果大小不匹配,原始库的行为是用断言直接崩溃,而新代码将首先调整multi_array的大小,然后而不是崩溃。所以,除非你有测试用例需要应用程序崩溃,否则没有测试用例可能会被这个更改破坏。
节省了无数的工作时间,防止了无数未被发现的bug 绝对胜过作者可能拥有的任何语义意识形态。在那里。这就是我的咆哮。不客气。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 为什么在C++中使用私有复制构造函数与删除复制构造函数
- 当从函数参数中的临时值调用复制构造函数时
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 使用复制构造函数复制双精度数组
- C 无可行的构造函数复制类型的变量
- 没有可行的构造函数复制类型 'MyString' 的数组元素
- 编译时,复制构造函数/复制分配和正常功能调用优化之间是否存在任何区别
- 如何最小化调用列表构造函数(复制构造函数)的次数?
- C 11矢量构造函数复制与范围
- 我定义了一个非复制构造函数;复制构造函数还会被隐式定义吗
- 可以将构造函数复制为转换运算符
- 将基类指针的构造函数复制到子类
- C++树类:构造函数/复制/内存泄漏
- 如何制作这个在模板构造函数复制中使用类型定义的类型的模板
- 将构造函数复制为模板化的成员函数
- 绕过私有复制构造函数/复制赋值C++
- C++通过构造函数复制对象
- 复制构造函数 - 复制C++中的对象
- 将带unique_ptr的类的构造函数复制到作为成员的抽象类