item21

返回对象时,不能返回引用;

其实在前几个item里就反复讲到operator的时候;

Widget& operator=(int rhs)

{

...

return *this;

}

这里就返回了引用;

但这个item里,作者又举出了反例;

const Widget operator*(const Widget&,const Widget&)

{

return Widget(....);

}

因为这样返回local 对象是很危险的,毕竟引用或指针所指的对象都消失了,还能操作它吗?很显然是很危险的。

大师说的有道理,嗯,今天到这。

原文地址:https://www.cnblogs.com/xiangshancuizhu/p/2734776.html