If you return a value (T operator...
), you will return a new object, a copy of *p
. If caller modifies the returned object, it won't affect your attribute variable. Returning by copy has a cost (CPU operations to create the copy + memory usage of the copied object). It also requires T to be capiable (to provide a valid copy constructor).
If you return by reference (T& operator...
), you will return the address of the object (in the end, it's very similar to returning a poinetr T*
, it costs the same, only syntax to use references is different than syntax to use pointers). If caller modifies the returned referenced object, it will affect your attribute variable (however, making the reference returned const T&
will prevent that).
Reference is preferable (faster and better in term of memory usage), as far as you can guarantee that the referenced variable remains alive while caller will use the reference. For instance, if you are returning a local object created by the function, it must be returned by copy, not by reference).
Read more here: What are the differences between a pointer variable and a reference variable in C++?