Reference is a great tool to improve the efficiency of code, especially for objects, when referenced as a parameter without the large area of the copy object itself caused by the space and time wasted. So sometimes we want to return a reference to a parameter for the return value of the parameter. Here we recall that the C function returns local variables to the attention of the aspects, you can also see my article. Let's discuss the function return reference or non-reference in C + +!!
1. Return a reference
/********************************************************************** * * Copyright (c) 2015,wk Studios * * Filen ame:a.h* * COMPILER:GCC VC 6.0 * * AUTHOR:WK * * time:2015 4 5 * **************************************** /#include <iostream>using std::cout;using std::cin;class test{public:test (int d =0): m_data (d) {cout<< "Create Test Obj:" <<this<< "\ n";} Test (const test &t) {cout<< "Copy Test Obj:" <<this<< "\ n"; m_data = T.m_data;} test& operator= (const Test &t) {cout<< "Assgin:" <<this<< ":" <<&t<< "\ n"; if ( This! = &t) {m_data = T.m_data;} return *this;} ~test () {cout<< "Free Test Obj:" <<this<< "\ n";} int GetData () Const{return m_data;} void print () {cout<<m_data<< "\ n";} Private:int m_data;};/ /Way One test& fun (const Test &t) {int value = T.getdata (); Test tmp (value); return tmp;} void Main () {Test T (10); Test t1;t1 = Fun (t);cout<< "M_data of T1 is: "; T1.print (); Test t2 = Fun (t);cout<< "m_data of T2 is:"; T2.print ();}
2. Return non-reference
<span style= "color: #333333;" >/********************************************************************** * * Copyright (c) 2015,WK Studios * * F ilename:a.h* * COMPILER:GCC VC 6.0 * * AUTHOR:WK * * time:2015 4 5 * ************************************ /#include <iostream>using std::cout;using std::cin;class test{public:test ( int d=0): m_data (d) {cout<< "Create Test Obj:" <<this<< "\ n";} Test (const test &t) {cout<< "Copy Test Obj:" <<this<< "\ n"; m_data = T.m_data;} test& operator= (const Test &t) {cout<< "Assgin:" <<this<< ":" <<&t<< "\ n"; if ( This! = &t) {m_data = T.m_data;} return *this;} ~test () {cout<< "Free Test Obj:" <<this<< "\ n";} int GetData () Const{return m_data;} void print () {cout<<m_data<< "\ n";} Private:int m_data;};/ /Way one Test fun (const test &t) {int value = T.getdata (); Test tmp (value); return tmp;} void Main () {Test T (10); TesT t1;t1 = Fun (t);cout<< "m_data of T1 is:"; T1.print (); Test t2 = Fun (t);cout<< "m_data of T2 is:"; T2.print ();} </span>
Come down and summarize the return references and non-references:
Thinking about C + + functions 2 (the difference between a function return reference and a return non-reference)