重载数组下标[]运算符缓慢

ste*_*ano 5 c++ performance operator-overloading

我用c ++编写了自己的Array类,并重载了数组下标[]运算符,代码:

inline dtype &operator[](const size_t i) { return _data[i]; }
inline dtype operator[](const size_t i) const { return _data[i];}
Run Code Online (Sandbox Code Playgroud)

其中_data是指向包含数组的内存块的指针.分析表明,这个重载运算符单独占用总计算时间的10%(在长蒙特卡罗模拟中,我使用g ++进行最大优化编译).这似乎很多,任何想法为什么会这样?

编辑:dtype是double,而_data是指向double数组的指针

Chn*_*sos 2

const的重载实际上operator[]是返回一个副本而不是dtype const &. 如果 dtype 很大,则副本可能会很昂贵。

像这样进行原型设计应该可以解决这个问题:

inline dtype const & operator[] (const size_t i) const { return _data[i]; }
Run Code Online (Sandbox Code Playgroud)