简体   繁体   中英

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?

The references allow tsplit() to manipulate the pointers themselves, not just the contents of what is being pointed to (each tnode ). The function probably allocates memory or such.

This is a something of a typical/classical "return by reference" (also called out parameter ) issue, and the return values here are pointers.

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. Ie 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.

yeah it makes sense , If you allocate new memory inside void tsplit(tnode t, tnode &l, tnode &r, int x)

like t = new struct node;

then it will be reflected back only if , you declared it as reference to pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM