about the reference fuction

D

Daqian Yang

Hi all,

I have a question here, could anyone tell me what the differences bw
those funtions:

DataType move(DataType a){return a}

DataType &move(DataType &a){return a}

thanks!
 
R

Ron Natalie

Daqian Yang said:
Hi all,

I have a question here, could anyone tell me what the differences bw
those funtions:

DataType move(DataType a){return a}

DataType &move(DataType &a){return a}
The return value of the former is a copy of the value it is passed.
The return value of the latter is a reference to the same value.
 
J

jeffc

Daqian Yang said:
Hi all,

I have a question here, could anyone tell me what the differences bw
those funtions:

DataType move(DataType a){return a}

DataType &move(DataType &a){return a}

The argument: in the second example it gets passed by reference instead of
value. A new copy is not made when the function is called. If it changes
in the function, it will change for the caller too (unlike the first
example).

The return type: in the second example, the return value is passed by
reference instead of value. This one is much more tricky and error prone.
It's similar in theory to using a pointer. You are not giving thecaller an
automatically created object. You are giving them a reference to some
storage that better have been dynamically created, or already existed. Then
you have to think about who is responsible for this storage after the call.
If you don't understand what I'm talking about, then don't use it until
you've learned a lot more! :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,054
Latest member
LucyCarper

Latest Threads

Top