C++中函数返回引用的注意事项

C++函数的返回过程基本上可以分为两个阶段:返回阶段和绑定阶段。根据需要绑定的值的类型将产生不同的情况,下文是中国E盟技术频道小编为大家介绍的C++中函数返回引用的注意事项,希望对你学习有帮助!
1,引用函数的参数,当然该参数也是一个引用


const string &shorterString(const string &s1,const string &s2)
{
return s1.size()<s2.size()?s1:s2;
}


以上函数的返回值是引用类型。无论返回s1或是s2,调用函数和返回结果时,都没有复制这些string对象。简单的说,返回的引用是函数的参数s1或s2,同样s1和s2也是引用,而不是在函数体内产生的。函数体内局部对象是不能被因哟个的,因为函数调用完局部对象会被释放。

2,千万不要返回局部对象的引用


const string &mainip(const string &s)
{
string ret=s;
return ret;
}


当函数执行完毕,程序将释放分配给局部对象的存储空间。此时,对局部对象的引用就会指向不确定的内存。
3,不能返回函数内部定义的对象。在类的成员函数中,返回引用的类对象,当然不能是函数内定义的类对象(会释放掉),一般为this指向的对象,典型的例子是string类的赋值函数。


<SPAN style="COLOR: #000066; FONT-SIZE: 16px">String& String::operator =(const String &str) //注意与“+”比较,函数为什么要用引用呢?a=b=c,可以做为左值
{
if (this == &str)
{
return *this;
}
delete [] m_string;
int len = strlen(str.m_string);
m_string = new char[len+1];
strcpy(m_string,str.m_string);
return *this;
}</SPAN>


这与sting类中的“+”运算符重载不一样。“+”运算符的重载不能返回引用,因为它返回的是在函数内定义的类对象,附上代码。


<SPAN style="COLOR: #000066; FONT-SIZE: 16px">String String::operator +(const String &str)
{
String newstring;
if (!str.m_string)
{
newstring = *this;
}
else if (!m_string)
{
newstring = str;
}
else
{
int len = strlen(m_string)+strlen(str.m_string);
newstring.m_string = new char[len+1];
strcpy(newstring.m_string,m_string);
strcat(newstring.m_string,str.m_string);
}
return newstring;
}</SPAN>


4,引用返回左值(上例的=赋值也是如此,即a=b=c是可以的)


char &get_val(string &str,string::size_type ix)
{
return str[ix];
}
使用语句调用:
string s("123456");
cout<<s<<endl;
get_val(s,0)='a';
cout<<s<<endl;


最后转上一段code作为总结。


<span style="font-size:16px;color:#000066;">#include<iostream>
using namespace std;
string make_plural(size_t,const string&,const string&);
const string &shorterString(const string &,const string &);
const string &mainip(const string&);
char &get_val(string &,string::size_type);
int main(void)
{
cout<<make_plural(1,"dog","s")<<endl;
cout<<make_plural(2,"dog","s")<<endl;

string string1="1234";
string string2="abc";
cout<<shorterString(string1,string2)<<endl;

cout<<mainip("jiajia")<<endl;


string s("123456");
cout<<s<<endl;
get_val(s,0)='a';

cout<<s<<endl;

getchar();
return 0;
}
//返回非引用
string make_plural(size_t i,const string &word,const string &ending)
{
return (i==1)?word:word+ending;
}
//返回引用
const string &shorterString(const string &s1,const string &s2)
{
return s1.size()<s2.size()?s1:s2;
}
//禁止返回局部对象的引用(我的dev c++ 没有报错,比较可怕)
const string &mainip(const string &s)
{
string ret=s;
return ret;
}
//引用返回左值
char &get_val(string &str,string::size_type ix)
{
return str[ix];
}</span>

以上就是中国E盟技术频道小编收集的关于C++中函数返回引用的注意事项,小编建议对这方面感兴趣的可以多多关注中国E盟技术频道发布的内容。