【问题标题】:Is it good style to return a reference in this case?在这种情况下返回参考是一种好的风格吗?
【发布时间】:2016-03-03 08:59:35
【问题描述】:

我刚刚偶然发现了 Evan Teran 在 Split a string in C++? 上的回答,他在其中通过引用获取了一个向量,对其进行了修改并返回了它的引用。

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
  std::stringstream ss(s);
  std::string item;
  while (std::getline(ss, item, delim)) {
    elems.push_back(item);
  }
  return elems;
}

这种风格好吗?我看到好处是直接使用结果,就像在

std::vector<std::string> vec;
unsigned int uiSize = split("ssad asda", ' ', vec).size();

而不是

std::vector<std::string> vec;
split("ssad asda", ' ', vec);
unsigned int uiSize = .size()

有什么缺点吗?据我所知,反对返回引用的主要原因是人们可能会返回一个在返回后被破坏的局部变量的引用。这在这里不适用,因为对象不是本地的,而是作为参数提供给方法的。

【问题讨论】:

  • 我认为这个用例返回参考没有问题。就像operator&lt;&lt;
  • 这是一个合理的做法,用于链接命令。例如,这种方法用于operator&lt;&lt; 进行打印。对于函数调用而不是运算符仍然有用。

标签: c++ pass-by-reference


【解决方案1】:

代码

std::vector<std::string> &split(const std::string &s, char delim, std::vector<std::string> &elems) {
  std::stringstream ss(s);
  std::string item;
  while (std::getline(ss, item, delim)) {
    elems.push_back(item);
  }
  return elems;
}

被误导了:它更像是一个append_lines 而不是split 函数。

但鉴于此,返回对向量的引用是有意义的,是的。按值返回通常不能从移动语义中受益,因此会产生一些不必要的开销。而void 结果可能会使调用代码变得非常笨拙和尴尬。

【讨论】:

    猜你喜欢
    • 2013-04-17
    • 1970-01-01
    • 1970-01-01
    • 2017-03-31
    • 2010-11-04
    • 2011-08-22
    • 1970-01-01
    • 2020-11-29
    • 2017-12-14
    相关资源
    最近更新 更多