c++classgettermember-variables

Should getters return small, trivial data members by reference or by value?


If I have a class that has many int, float, and enum data members, is it considered efficient and/or good practice to return them as references rather than copies, and return constant references where no changes should be made, or is there a reason I should return them as copies?


Solution

  • There is no reason to return primitive types such as int and float by reference, unless you want to allow them to be changed. Returning them by reference is actually less efficient because it saves nothing (ints and pointers are usually the same size) while the dereferencing actually adds overhead.