I have a Text
class that has certain methods that return a pointer to itself, allowing calls to be chained. (The reason being I merely like how the chaining looks and feels, honestly!)
My question is, which is generally better in practice (in terms of safety > versatility > performance)? Returning and using References? Or Returning and using Pointers?
An example of both, starting with the Pointer version:
class Text{ public: Text * position(int x, int y){ /* do stuff */ return this; } Text * write(const char * string); Text * newline(); Text * bold(bool toggle); Text * etc(); ... }; textInstance.position(0, 0)->write("writing an ")->bold(true)->write("EXAMPLE"); textInstance.position(20, 100) ->write("and writing one across") ->newline() ->write("multiple lines of code");
versus the Reference version:
class Text{ public: Text & position(int x, int y){ /* do stuff */ return *this; } Text & write(const char * string); Text & newline(); Text & bold(bool toggle); Text & etc(); ... }; textInstance.position(0, 0).write("writing an ").bold(true).write("EXAMPLE"); textInstance.position(20, 100) .write("and writing one across") .newline() .write("multiple lines of code");
This question is related to
c++
pointers
reference
coding-style
return
Very interesting question.
I don't see any difference w.r.t safety or versatility, since you can do the same thing with pointer or reference. I also don't think there is any visible difference in performance since references are implemented by pointers.
But I think using reference is better because it is consistent with the standard library. For example, chaining in iostream is done by reference rather than pointer.
Since nullptr
is never going to be returned, I recommend the reference approach. It more accurately represents how the return value will be used.
It's canonical to use references for this; precedence: ostream::operator<<
. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.
Source: Stackoverflow.com