值传递与引用传递的一个例子

来源:互联网 发布:蓝牙模块和51单片机 编辑:程序博客网 时间:2024/06/15 17:24

如果函数的返回值是一个对象,有些场合用“引用传递”替换“值传递”可以提高效率。而有些场合只能用“值传递”而不能用“引用传递”,否则会出错。

例如:

class String{//赋值函数String & operate=(const String &other);//相加函数,如果没有friend修饰则只许有一个右侧参数friend String operate+(const String &s1,const String &s2);private:char *m_data;}
String的赋值函数operate = 的实现如下:

String & String::operate=(const String &other){if(this==&other)return *this;delete m_data;m_data=new char[strlen(other.data)+1];strcpy(m_data,other.m_data);return *this;}

对于赋值函数,应当用“引用传递”的方式返回String对象。如果用“值传递”的方式,虽然功能仍然正确,但由于return语句要把 *this 拷贝到保存返回值的外部存储单元之中,增加了不必要的开销,降低了赋值函数的效率。例如:

 String a,b,c; 
… 
 a = b;  // 如果用“值传递” ,将产生一次 *this 拷贝 
 a = b = c; // 如果用“值传递”,将产生两次 *this 拷贝 
String的相加函数operate + 的实现如下:

String String::operate+(const String &s1,const String &s2){String temp;delete temp.m_data;temp.m_data=new char[strlen(s1.m_data)+strlen(s2.m_data)+1];strcpy(temp.m_data,s1.m_data);strcat(temp.m_data,s2.m_data);return temp;}
对于相加函数,应当用“值传递”的方式返回String对象。如果改用“引用传递”,那么函数返回值是一个指向局部对象temp的“引用”。由 于temp在函数结束时被自动销毁,将导致返回的“引用”无效。例如:
 c = a + b; 
此时 a + b 并不返回期望值,c 什么也得不到,流下了隐患。 

0 0
原创粉丝点击