【问题标题】:Return string vs Passing string by reference to update the value返回字符串 vs 通过引用传递字符串以更新值
【发布时间】:2018-07-11 14:05:01
【问题描述】:

以下两个函数中有什么好的编程习惯:

  1. 这个:

    std::string buildvalue(const std::string &in) {
        std::string out;
        out = // Do some calulation bases on input
        return out;
    }
    
  2. 或者这个:

    void buildvalue(const std::string &in, std::string &out) {
        out = // Do some calulation bases on input
    }
    

注意 2 函数是调用者可能传递非空字符串。有没有需要注意的地方。

【问题讨论】:

  • 1(这必须至少 16 个字符长 :))
  • 两者都有一些优点和缺点,值得在特定情况下考虑
  • 返回值优化(尤其是复制省略)和移动语义在很大程度上使 1 成为一个非常好的解决方案。
  • 用户将非空字符串传递给out 与将第一个解决方案的结果分配给非空字符串的用户没有什么不同。我不明白为什么要格外小心。
  • 除非你必须返回多个值,即使那样你也可以不用输出参数,你应该返回函数的输出。

标签: c++ stdstring c++98


【解决方案1】:

在第一种情况下,编译器将能够优化返回值。它将返回值放在调用函数中。例如,

std::string foo(...) { ... }

// ...

std::string result = foo(...);

编译器会将 foo 返回值放在结果点上。 它使我们从引用参数和过早的变量声明中解脱出来。 略 C++17: 相反 const std::string& 你可以使用 std::string_view。它的优点是在以下情况下创建临时 std::string 是可选的:

void foo(const std::string&);
// ...
foo("hello world"); // here will be create std::string object

使用 std::string_view (c++17)

void foo(std::string_view);
// ...
foo("hello world"); // more productive

+ std::string 有操作符 std::string_view,将其引向 std::string_view

【讨论】:

  • 谢谢你的意见,另外我还在用98版本。
  • @PURVESHPATEL 您可能想标记您的问题c++-98 - 这是非常相关的信息。
猜你喜欢
  • 2017-03-10
  • 2014-08-11
  • 2017-07-25
  • 2016-07-05
  • 1970-01-01
  • 2013-04-07
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
相关资源
最近更新 更多