这是一个好主意,总是返回成员变量getter的引用? [英] Is it a good idea to always return references for member variable getters?
问题描述
如果我有一个类有许多 int
, float
和 enum
成员变量,它被认为是高效的和/或良好的做法,返回它们作为引用而不是副本,并返回常量引用,不应该做任何更改?
If I have a class that has many int
, float
, and enum
member variables, 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?
推荐答案
没有理由返回原始类型,例如 int
和 float
作为引用,除非要允许它们更改。通过引用返回它们实际上效率较低,因为它不保存任何内容( int
s和指针通常大小相同),而取消引用实际上增加了开销。
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 (int
s and pointers are usually the same size) while the dereferencing actually adds overhead.
这篇关于这是一个好主意,总是返回成员变量getter的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!