为什么最好写func(const Class& value)? [英] Why is it preferable to write func( const Class &value )?

查看:114
本文介绍了为什么最好写func(const Class& value)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么要使用 func(const Class& value)而不是 func(Class value)?当然,现代编译器将使用任何语法做最高效的事情。

Why would one use func( const Class &value ) rather than just func( Class value )? Surely modern compilers will do the most efficient thing using either syntax. Is this still necessary or just a hold over from the days of non-optimizing compilers?


  • 只是为了添加,gcc会产生类似的汇编代码输出为任一语法。也许其他编译器不会?

  • Just to add, gcc will produce similar assembler code output for either syntax. Perhaps other compilers do not?

显然,情况并非如此。我有一些代码的印象很久以前,gcc做到了这一点,但实验证明这是错误的。应归功于Michael Burr,如果在此处提供类似问题的答案,则会被提名。

Apparently, this is just not the case. I had the impression from some code long ago that gcc did this, but experimentation proves this wrong. Credit is due to to Michael Burr, whose answer to a similar question would be nominated if given here.

推荐答案

2个签名之间有2个大的语义差异。

There are 2 large semantic differences between the 2 signatures.

第一种是在类型名称中使用& 。这表示该值通过引用传递。删除这将导致对象通过值,它本质上将一个对象的副本传递到函数(通过副本构造函数)。对于只需要读取数据(典型的 const& )的操作,执行对象的完整副本会产生不必要的开销。

The first is the use of & in the type name. This signals the value is passed by reference. Removing this causes the object to be passed by value which will essentially pass a copy of the object into the function (via the copy constructor). For operations which simply need to read data (typical for a const &) doing a full copy of the object creates unnecssary overhead. For classes which are not small or are collections, this overhead is not trivial.

第二个是使用 const 。这防止函数通过 value 引用意外修改值的内容。它允许调用者一些测量的保证值不会被函数突变。是的,传递一个副本给了调用者在许多情况下更深的保证这一点。

The second is the use of const. This prevents the function from accidentally modifying the contents of value via the value reference. It allows the caller some measure of assurance the value will not be mutated by the function. Yes passing a copy gives the caller a much deeper assurance of this in many cases.

这篇关于为什么最好写func(const Class& value)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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