gpt4 book ai didi

c++ - 重载数组下标 [] 运算符慢

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:44:17 24 4
gpt4 key购买 nike

我用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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com