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");
The difference between pointers and references is quite simple: a pointer can be null, a reference can not.
Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).
Here it looks like references are more appropriate.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With