c++ - 返回字符串与通过引用传递字符串以更新值

标签 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 函数是调用者可能传递非空字符串。有没有什么需要注意的地方。

最佳答案

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

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

关于c++ - 返回字符串与通过引用传递字符串以更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51287587/

相关文章:

c++ - 在 C : How to properly write some sort of "delete/dispose" function? 中使用 C++ 类

c++ - std::atomic 是否有可能使类的复杂成员函数成为原子?

c++ - 有没有办法将 QVariant 与 QVector 一起使用?

c++ - 为我的字符串类实现 reverse_iterator(还有 rbegin() 和 rend() 方法)

c++ - 无法理解此语句 - 运算符后的返回类型

c++ - 从动态分配的解引用指针默认初始化非常量引用函数参数是否会造成内存泄漏?

c++ - 使用通用私有(private)成员设计模板类

c++ - 表达式必须具有整数或枚举类型 Char*

c++ - 为什么 C++11 使 std::string::data() 添加一个空终止字符?

c++ - 尝试随机播放 std::vector 时出错