返回字符串vs通过引用传递字符串以更新值

时间:2018-07-11 14:05:01

标签: c++ stdstring c++98

以下两个功能中什么是好的编程习惯:

  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 个答案:

答案 0 :(得分:0)

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

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

相关问题