string sample = "This is a sample";
cout << sample<< endl;
string i1 = printval(sample) = "haha";
cout<< i1 <<endl;
What does the function printval refer to? Because it should be a reference should be bound to something. Im not really sure what does that function refer to. Thanks
I remove the reference and just declare an ordinary function with a reference as parameter
Because they return the same output. and since i am returning the str to the function w/c is reference to the sample variable making the function a reference doesnt make any sense to me.
IF its not so much to ask can you give me an example that shows the difference of using a reference function?
std::string& foo( std::string& str ) { return str ; }
returns an lvalue - it returns an expression that identifies a non-temporary object.
Reference to the non-temporary object str is returned.
std::string bar( std::string& str ) { return str ; }
returns a prvalue (pure rvalue) - it returns an expression that identifies an anonymous temporary object.
Conceptually, an anonymous copy of str is made and that temporary object is returned by value.
> example that shows the difference
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <string>
std::string& foo( std::string& str ) { return str ; }
std::string bar( std::string& str ) { return str ; }
int main()
{
std::string s ;
std::string& fine = foo(s) ; // fine, reference to non-temporary object
const std::string& also_fine = foo(s) ; // fine, reference to const extends the life of the temporary object
std::string& not_fine = bar(s) ; // *** error *** reference to non-const can't bind to a temporary object
}