为什么要退回“const&”? [英] why reture "const &"?

查看:72
本文介绍了为什么要退回“const&”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模板< class T>

inline T const& max(T const& a,T const& b)

{

//如果a< b然后使用b否则使用

返回< b?b:a;

}


非常感谢!!

template <class T>
inline T const& max (T const& a, T const& b)
{
// if a < b then use b else use a
return a<b?b:a;
}

thanks very much!!

推荐答案

ze *** ****@gmail.com 写道:

为什么要退回const&>

模板< class T>
内联T const& max(T const& a,T const& b)
{
//如果a< b然后使用b否则使用
返回< b?b:a;
}

why reture "const &"?

template <class T>
inline T const& max (T const& a, T const& b)
{
// if a < b then use b else use a
return a<b?b:a;
}




防止像
这样的暴行br />
std :: max(a,b)= 2;


并允许传递和返回rvalues。

Jonathan



To prevent atrocities like

std::max(a, b) = 2;

and to allow passing and returning of rvalues.
Jonathan


" Jonathan Mcdougall" <乔*************** @ DELyahoo.ca>在消息中写道

新闻:Kc ******************** @ weber.videotron.net ...
"Jonathan Mcdougall" <jo***************@DELyahoo.ca> wrote in message
news:Kc********************@weber.videotron.net...
ze*******@gmail.com 写道:
>
>为什么退回const&>
>
模板<类T>
内联T const& max(T const& a,T const& b)
{
//如果a< b然后使用b否则使用
返回< b?b:a;
}
>
> why reture "const &"?
>
template <class T>
inline T const& max (T const& a, T const& b)
{
// if a < b then use b else use a
return a<b?b:a;
}



要防止像

std这样的暴行:: max(a,b)= 2;



To prevent atrocities like

std::max(a, b) = 2;




为什么这是一个暴行?您可能希望将a和b的最大值分配给2.


DW



Why is that an atrocity? You might want to assign the max of a and b to 2.

DW


zealotcat at gmail。 com写道:
zealotcat at gmail.com wrote:
template< class T>
inline T const& max(T const& a,T const& b)
{
//如果a< b然后使用b否则使用
返回< b?b:a;
}
template <class T>
inline T const& max (T const& a, T const& b)
{
// if a < b then use b else use a
return a<b?b:a;
}




如果按值(T)返回通过const引用(T const&),你

获得最大值的副本,而不是原始副本。当通过

(const)引用返回时,类T不需要有一个复制构造器。


BTW,const是必要的,因为你的参数也是const

引用。您可能会考虑使用非const版本




模板< class T>

inline T& max(T& a,T& b)

{

返回< b?b:a;

}


另请参见 http:// www.aristeia.com/Papers/C++Re...umns/jan95.pdf

亲切的问候,


Niels Dekker
http://www.xs4all.nl/~nd/dekkerware


这篇关于为什么要退回“const&amp;”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆