【问题标题】:Can I pass a default value to a reference for a std::string ?我可以将默认值传递给 std::string 的引用吗?
【发布时间】:2013-11-17 11:50:28
【问题描述】:
void doStuff( std::string const & s1, std::string const & s2="");

我想知道对于 s2 字符串,这段代码在 C++ 中是否合法。 我想要一个默认参数,但传递一个引用并有一个空字符串作为默认值。会创建一个临时的,并且引用会指向那个临时的,还是非法的 C++?

【问题讨论】:

    标签: c++ reference constants default-arguments


    【解决方案1】:

    是的,这是合法的。 const 将确保暂时持续到功能 doStuff 完成。

    § 12.2.5

    在函数调用 (5.2.2) 中临时绑定到引用参数会一直存在,直到包含调用的完整表达式完成为止。

    【讨论】:

      【解决方案2】:

      会更好

      void doStuff( std::string const & s1, std::string const & s2 = std::string());
      

      为了避免额外的临时const char *。 (您的变体有 2 个临时变量:const char * 和空 std::string)。

      或者,使用用户定义的文字 (C++14):

      void doStuff( std::string const & s1, std::string const & s2 = ""s);
      

      【讨论】:

      • 仅供参考:也可以使用std::string const & s2 = {}作为与c++11兼容的简短版本
      【解决方案3】:

      为了理解语义,最好拆分原始语句。

      void doStuff( std::string const & s1, std::string const & s2="");
      

      分成两个语句

      void doStuff( std::string const & s1, std::string const & s2);
      doStuff( SomeString, "" );
      

      在函数的调用中,第二个参数被隐式转换为 std::string 类型的对象:

      s2 = std::string( "" );
      

      所以实际上在函数体中你将拥有

      std::string const &s2 = std::string("");

      即常量引用 s2 将引用临时对象 std::string( "" )。

      【讨论】:

        猜你喜欢
        • 2011-07-17
        • 1970-01-01
        • 2015-01-11
        • 2016-12-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-26
        • 2022-11-02
        相关资源
        最近更新 更多