Why is it preferable to write func( const Class &v

2019-06-24 14:36发布

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?

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

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.

9条回答
叼着烟拽天下
2楼-- · 2019-06-24 14:54

The first example is pass by reference. Rather than pass the type, C++ will pass a reference to the object (generally, references are implemented with pointers... So it's likely an object of size 4 bytes)... In the second example, the object is passed by value... if it is a big, complex object then likely it's a fairly heavyweight operation as it involves copy construction of a new "Class".

查看更多
\"骚年 ilove
3楼-- · 2019-06-24 15:06

Here are the differences between some parameter declarations:

                           copied  out  modifiable
func(Class value)           Y       N    Y
func(const Class value)     Y       N    N
func(Class &value)          N       Y    Y
func(const Class &value)    N       N    N

where:

  • copied: a copy of the input parameter is made when the function is called
  • out: value is an "out" parameter, which means modifications made within func() will be visible outside the function after it returns
  • modifiable: value can be modified within func()

So the differences between func(Class value) and func(const Class &value) are:

  • The first one makes a copy of the input parameter (by calling the Class copy constructor), and allows code inside func() to modify value
  • The second one does not make a copy, and does not allow code inside func() to modify value
查看更多
Rolldiameter
4楼-- · 2019-06-24 15:10

If you use the former, and then try to change value, by accident, the compiler will give you an error.

If you use the latter, and then try to change value, it won't.

Thus the former makes it easier to catch mistakes.

查看更多
登录 后发表回答