C++对象传递

如果函数的返回值是一个对象,有些场合用“引用传递”替换“值传

递”可以提高效率。而有些场合只能用“值传递”而不能用“引用传递”,否则会

出错。

例如:

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;

高质量C++/C 编程指南,v 1.0

2001 Page 39 of 101

m_data = new char[strlen(other.data)+1];

strcpy(m_data, other.data);

return *this; // 返回的是 *this 的引用,无需拷贝过程

}

对于赋值函数,应当用“引用传递”的方式返回String 对象。如果用“值传递”的

方式,虽然功能仍然正确,但由于return 语句要把 *this 拷贝到保存返回值的外部存

储单元之中,增加了不必要的开销,降低了赋值函数的效率。例如:

String a,b,c;

a = b; // 如果用“值传递”,将产生一次 *this 拷贝

a = b = c; // 如果用“值传递”,将产生两次 *this 拷贝

String 的相加函数operate + 的实现如下:

String operate+(const String &s1, const String &s2)

{

String temp;

delete temp.data; // temp.data 是仅含‘\0’的字符串

temp.data = new char[strlen(s1.data) + strlen(s2.data) +1];

strcpy(temp.data, s1.data);

strcat(temp.data, s2.data);

return temp;

}

对于相加函数,应当用“值传递”的方式返回String 对象。如果改用“引用传递”,

那么函数返回值是一个指向局部对象temp 的“引用”。由于temp 在函数结束时被自动

销毁,将导致返回的“引用”无效。例如:

c = a + b;

此时 a + b 并不返回期望值,什么也得不到,流下了隐患。

原文地址:https://www.cnblogs.com/Jonas/p/1541504.html