条款21:必须返回对象的时候,不要妄想使其返回reference

//先看看下面这个例子
class Rational{
public:
    Rational(int num, int denu)
    :numirator(num), denumirator(denu);
    const Rational operator*(const Rational & lhs, const Rational & rhs);//注意这里的返回类型
private:
    int numirator;
    int denumirator;
};
operator返回的是一个value而不是一个reference,如果想要这个函数返回一个reference的话(用来减少返回的时候拷贝带来的开销),可能希望像下面这样做:
1.在函数中使用new在heap上创建对象而不是在stack上创建对象:
Rational & operator(const Rational & lhs, const Rational & rhs)
{
    Retional result = new Rational(lhs.numirator + rhs.numirator, lhs.denumirator *         rhs.denumirator);
    return result;
}
但是如果这么做的话谁又来保证客户可以安然无恙的将资源合理的释放呢。
2.在函数内部用static对象来取代临时变量,像下面这样:
const Rational & operator*(const Rational & lhs, const Rational & rhs)
{
    static Rational result;
    Rational = Ratioanl(lhs.numirator * rhs.numirator, lhs.denumirator * rhs.denumirator);
    return result;
}

首先,加入static可定会对多线程的情况带来一些麻烦,再者看看下面这样的代码:

Rational a, b, c, d;
if(a * b == c * d);
//相当于if(operator*(a, b) == operator*(c, d))
  显然,这两个operator*返回的static变量肯定是指向同一个的,那么这个if必定等于1,毫无疑问,这里就可以看出这样做也是行不通的。
 
  其实正常的情况就是返回一个value就可以了,虽然可能带来效率上的损失(只是可能,现代的编译器有的都能消除这种情况带来的损失),这种损失也可以使用std::move来加以弥补。
 
  小结:绝对不要返回一个pointer或者reference指向一个local stack对象, 或者是一个reference指向一个heap allocated对象,或者返回一个local static对象而且又可能同时会用到这个local static对象。
原文地址:https://www.cnblogs.com/-wang-cheng/p/4858676.html