c++pointersreferencetreap

What is the difference between passing a pointer to function and passing reference of pointer to function?


So, I have a structure

struct node
{
    node * l;
    node * r;
};

Then, there is

typedef node* tnode;

What I don't understand is this function:

void tsplit(tnode t, tnode &l, tnode &r, int x)

As I get it, we pass t to tsplit() as a pointer to a structure, than we pass two references of pointers to structures of the same type. Why can't we just pass pointers instead of their references? Does it makes any sense?


Solution

  • Yes it makes sense. Generally you can treat references as pointers (with some restrictions). So you could change references to pointers in your example. Of course the syntax would also change in the, but we don't need to bother with it. Your example would look like:

    void tsplit(tnode t, tnode *l, tnode *r, int x)

    So the difference is, that you can modify what is under l and r but not t, the typedef abstracts it, but you can expand it:

    void tsplit(node* t, node** l, node** r, int x)

    Now, the meaning is that you can change what is under t, but you cannot change the t itself, you can do this with l and r. In other words, you cannot change the reference target of t, but you can do it with r and l, because you have a reference to a reference (or pointer to a pointer).

    Why use references over pointers? Because pointers can be also used for different things, like changing ownership of the objects. The syntax would look the same, but the semantics are very different. People like to look at how things look, and immediately know what is the intention and the meaning behind it. I.e. deduct semantics from the syntax. References can be only used to pass variables, so you know what to expect just from the look of things.