传递值或const引用? [英] Pass by value or const reference?

查看:152
本文介绍了传递值或const引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一组良好规则来确定是否通过值或const引用

p>


  • 如果函数打算将参数更改为副作用,则通过非const引用获取

  • 如果函数未修改其参数,并且参数为
    原始类型,请按值。

  • 它通过const引用,除了在以下
    情况:如果该函数然后将需要复制的const
    引用,无论如何,取它的值。



    • 对于下面的构造函数,如何确定它?

        b $ b {
      public:
      A(string str):mStr(str){} //这里更好,
      //通过值或const引用?

      void setString(string str){mStr = str; } //这里怎么样?

      private:
      string mStr;
      };


      解决方案

      em>软件
      工程的好参考。 (它也可能过时,考虑到它
      谈论移动语义,从2003年开始。)



      一般规则很简单:pass class类型由const引用,
      和其他类型的值。有明显的例外:在
      保持标准库的约定,它也是
      通常的值通过迭代器和功能对象。



      任何其他都是优化,不应该进行,直到
      分析器说,你必须。


      There is a set of good rules to determine whether pass by value or const reference

      • If the function intends to change the argument as a side effect, take it by non-const reference.
      • If the function doesn't modify its argument and the argument is of primitive type, take it by value.
      • Otherwise take it by const reference, except in the following cases: If the function would then need to make a copy of the const reference anyway, take it by value.

      For constructor as following, how to determine it?

      class A
      {
      public:
          A(string str) : mStr(str) {} // here which is better, 
                                       // pass by value or const reference?
      
          void setString(string str)  { mStr = str; } // how about here?
      
      private:
          string mStr;
      };
      

      解决方案

      The article you site is not a good reference for software engineering. (It is also likely out of date, given that it talks about move semantics and is dated from 2003.)

      The general rule is simple: pass class types by const reference, and other types by value. There are explicit exceptions: in keeping with the conventions of the standard library, it is also usual to pass iterators and functional objects by value.

      Anything else is optimization, and shouldn't be undertaken until the profiler says you have to.

      这篇关于传递值或const引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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