21 Don't try to return a reference when you must return an object

Consider a class for representing rational numbers, including a function for multiplying two rationals together:

class Rational{
public:
  Rational(int numerator = 0, int denominator = 1);
...
private:
  int n, d;
friend const Rational operator*(const Rational& lhs, const Rational& rhs); 
/* why return type is const ?
Think about wrong operation if(a*b=c)
*/
};

This version of operator* is returning its result object by value.
There would not be any cost of destructor and constructor if it returns a reference instead. But remember that a reference is just a name, a name for some existing object. Whenever you see the declaration for a reference, you should immediately ask yourself what it is another name for, because it must be another name for something.
In the case of operator*, if the function is to return a reference, it must return a reference to some Rational object that already exists.

A function can create a new object in only two ways : on the stack or on the heap. Creation on the stack is accomplished by defining a local variable.Look at the example:

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

As the result , the function returns a reference to result, but result is a local object, and local objects are destroyed when the function exists.This version of operator* does not return a reference to a Rational, it returns a reference to an ex-Rational, which we cannot find any more.

Let us consider the possibility of constructing an object on the heap and returning a reference to it. Heap-based objects come into being through the use of new, so we can write a heap-based operator* like this:

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

The new question has come : who will apply delete to the object conjured up by the use of new ?

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容