Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Call Chaining; returning a pointer vs a reference?

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");
like image 494
Anne Quinn Avatar asked Oct 18 '25 18:10

Anne Quinn


2 Answers

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.

like image 200
Mark Avatar answered Oct 20 '25 08:10

Mark


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.

like image 22
David Avatar answered Oct 20 '25 08:10

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!