本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie
经验:绝不要返回pointer或reference指向一个local stack对象,或返回reference指向一个heap-allocated对象,或返回pointer或reference指向一个local static 对象而有可能同时需要多个这样的对象。
示例1:返回pointer或reference指向一个localstack对象
const Rational &operator*(const Rational &lhs, const Rational &rhs){
Rational result(lhs.n * rhs.n, lhs.d * rhs.d);
return result;
}
解析:operator*函数返回的是一个局部的对象,它在函数退出前已经被销毁了,函数退出后reference指向一个未定义的空间
示例2:返回pointer或reference指向一个heap-allocated对象
const Rational &operator*(const Rational &lhs, const Rational &rhs){
Rational *result = new Rational(lhs.n * rhs.n, lhs.d * rhs.d);
return *result;
}
解析:没有人负责对new出来的对象实施delete
示例3:返回pointer或reference指向一个local static对象
#include <iostream>
#include <string>
using namespace std;
struct Rational{
int n, d;
Rational(int nn, int dd): n(n), d(dd){}
};
const Rational &operator*(const Rational &lhs, const Rational &rhs){
static Rational result(lhs.n * rhs.n, lhs.d * rhs.d);
return result;
}
bool operator==(const Rational &lhs, const Rational &rhs){
return (lhs.n == rhs.n && lhs.d == rhs.d);
}
int main(){
Rational a(1,1), b(2,2), c(3,3), d(4,4);
cout << ((a * b) == (c * b)) << endl;
system("pause");
}
输出:
1
解析:
因为static对象是放在内存全局静态存储区的,两次乘积返回的都是指向同一个static对象的引用,所以不管a,b,c,d的值是多少,输出的结果都为是1,即相等。
纠正:
inline const Rational operator *(const Rational &lhs, const Rational &rhs)
{
return Rational(lhs.n * rhs.n, lhs.d * rhs. d);
}