我用c++写了自己的Array类,重载了数组下标[]运算符,代码:
inline dtype &operator[](const size_t i) { return _data[i]; }
inline dtype operator[](const size_t i) const { return _data[i];}
其中 _data 是指向包含数组的内存块的指针。分析表明,仅这个重载运算符就占用了总计算时间的大约 10%(在长时间的蒙特卡洛模拟中,我正在使用 g++ 进行最大优化编译)。这似乎很多,知道这是为什么吗?
已编辑:dtype 是double,_data 是指向double 数组的指针
最佳答案
operator[]
的 const
重载实际上返回一个拷贝而不是 dtype const &
。如果 dtype 很大,拷贝可能很昂贵。
像这样制作原型(prototype)应该可以解决这个问题:
inline dtype const & operator[] (const size_t i) const { return _data[i]; }
关于c++ - 重载数组下标 [] 运算符慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22864368/