I have written my own Array class in c++ and overloaded the array subscript [] operator, code:
inline dtype &operator[](const size_t i) { return _data[i]; }
inline dtype operator[](const size_t i) const { return _data[i];}
where _data is a pointer to the memory block containing the array. Profiling shows that this overloaded operator alone is taking about 10% of the overall computation time (on a long monte carlo simulation, and I am compiling using g++ with maximum optimization). This seems a lot, any idea why this is?
edited: dtype is a double, and _data is a pointer to an array of double
The subscript operator [] is normally used to access array elements. This operator can be overloaded to enhance the existing functionality of C++ arrays.
There isn't a double-subscript operator in C++. What you can do is overload operator[] to return an object that also overloads operator[] . This will enable you to write m[i][j] .
The ^ operator is weaker than + (but stronger than <<). Moral: You cannot change the operator precedence when overloading operators. Do not overload an operator if its precedence is not intuitive for the problem domain. The precedence of ^ is fine for XOR but not for raising to a power.
In order to overload the operator of indexing the elements of the array [], the operator function operator[]() must be implemented in the class. There are 2 ways to implement the operator function operator[](). These variants differ in returning a value from an operator function.
The const
overload of operator[]
is actually returning a copy instead of a dtype const &
. If dtype is big, the copy might be expensive.
Prototyping it like that should solve that problem :
inline dtype const & operator[] (const size_t i) const { return _data[i]; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With