传值 传引用 函数返回值

来源:互联网 发布:怎么重装mac系统 编辑:程序博客网 时间:2024/05/07 05:04

1.函数只能返回值,而不适合返回引用和指针的情况。
Never return a reference to a local object or to a dereferenced pointer initialized by new within the

function.
函数返回时不要返回一个局部对象的引用或函数体中new建立的指针。
这会导致下面问题的产生:
The function return references to objects that don't exist
因为函数返回(结束)时,局部对象将释放或析构,将导致返回的引用指向一个不存在的对象。
我们说:在能返回references时返回尽量使用返回references而不要返回value以提高效率,不能返回references时就

返回value。那么在什么情况下不能返回references?比较下面的几个函数:

Student returnStudent(Student s) { return s; }

const Student& returnStudent(const Student& s)

inline const Rational operator*(const Rational& lhs,
                         const Rational& rhs)
{
return Rational(lhs.n * rhs.n, lhs.d * rhs.d);
}

// incorrect
inline const Rational& operator*(const Rational& lhs,
                         const Rational& rhs)
{
return Rational(lhs.n * rhs.n, lhs.d * rhs.d);
}

这四个函数按功能分为两组,头两个一组,后面两个一组,在第一组中第二个函数效率比第一个好,因为它返回的是一

个引用。但在第二组中,如果你试图返回一个引用将得到一个错误,例如最后一个函数就是这样。因为它返回的是一个

函数体内建立的临时对象的引用,一旦函数返回,此临时对象也将毁灭。导致返回的引用的不确定性。而第二个函数返

回的不是一个局部对象的引用,它返回的是以参数形式传入给函数的对象的引用。

2.Prefer pass-by-reference to pass-by-value.
如果能够使用传引用,尽量使用传引用,而不要使用传值(包括函数参数和函数返回值)
这样做的好处有:
a.主要是用来提高效率。
b.有时可以避免对象切割问题。
建议:当处理函数参数时,如果不是build-in类型或类型较大,就使用引用,可以使用const来限制函数体中对引用的对象做修改。但是当处理函数返回值时必须考虑能否返回一个引用。

3.函数返回值(return value)时的一些优化问题
// the most efficient way to write a function returning
// an object
inline const Rational operator*(const Rational& lhs,
                                const Rational& rhs)
{
  return Rational(lhs.numerator() * rhs.numerator(),
                  lhs.denominator() * rhs.denominator());
}

// the less efficient way to write a function returning
// an object
inline const Rational operator*(const Rational& lhs,
                                const Rational& rhs)
{
  Rational result(lhs.numerator() * rhs.numerator(),
                  lhs.denominator() * rhs.denominator());
  return result;
}

// the most inefficient way to write a function returning
// an object
inline const Rational operator*(const Rational& lhs,
                                const Rational& rhs)
{
  Rational result = Rational(lhs.numerator() * rhs.numerator(),
                             lhs.denominator() * rhs.denominator());
  return result;
}

在函数体中进行函数定义时,尽量避免临时object的产生和赋值运算(assignment),减少Constructor和Destructor,以提高效率。 

原创粉丝点击