I'm struggling to understand some code from "Ray Tracing in One Weekend" chapter 3.1.
We have a 3d vector class defined, and are overloading some operators. The following two lines confuse me:
double operator[](int i) const { return e[i]; }
double& operator[](int i) { return e[i]; }
From what I understand the first line runs when the object is a const and returns e[i] by value. The second line runs when the object is not const and returns e[i] by reference. What is the point in doing this? I think there's some potential for speedup by using references to mutable objects instead of returning them by value. Are there any other reasons?
CodePudding user response:
When the operator returns by non-const reference, the value can be modified by the caller. Normally, the const version would return const reference, but in case of double
, returning by value is just as fast.
CodePudding user response:
A non-‘’’const’’’ function can only be called on a mutable object. A const function can be called on either a ‘’’const’’’ or non-‘’’const’’’ object, but will default to the mutable function. The mutable function allows the object to access a reference the double value (therefore it can be modified). The ‘’’const’’’ function lets a const object access the double value; it returns a value because it cannot modify the object. It is unlikely to have any performance impact; both a reference and a double are likely to have 64 bits (on a modern desktop), although this is an implementation detail and will likely be optimized as needed by the compiler anyways.