[CSI] Returning Pass-by-Reference

Mikhail Nesterenko mikhail at cs.kent.edu
Thu Aug 12 16:58:34 EDT 2021


> 
> I have another question about returning pass-by-reference. What does it mean to return something with pass-by-reference and value?
>

Same semantics as pass-by-reference parameter: the return by reference
returns another name of the memory location of the variable in the
return statement. For example:


       int& func(){
       	    return x;
       }


func() returns the location of "x". One has to be very careful with
this return since, if "x" is automatic, then it gets dealloacated
before it is used. Here is an extended example of using
return-by-reference:

   http://antares.cs.kent.edu/~mikhail/classes/cs3.s21/Examples/Procedural/funcReference.cpp


> Also In the operator overloading function that we worked on
> yesterday, what would happen if you returned it by value?
> 

A regular return or return-by-value makes a copy of the value beging
returned. That is

       int func(){
            return x;
       }

func() returns a copy of "x". 

Thanks,
--
Mikhail


More information about the cs13001 mailing list