什么时候函数应该使用cstrings而不是字符串? (C ++)

时间:2012-06-03 04:58:52

标签: c++ string function c++11 parameter-passing

所以我一直在探索folly - Facebook的开源库,它们的大多数实用功能都采用cstrings而不是字符串。他们为什么这样做呢?这些示例传递了对std :: string的引用,并将其隐式转换为cstring。以下是他们的一个示例功能,我希望这个问题集中在:

如何调用该函数:

// Multiple arguments are okay, too. Just put the pointer to string at the end.
toAppend(" is ", 2, " point ", 5, &str);

内部Conv.h

/**
* Everything implicitly convertible to const char* gets appended.
*/
template <class Tgt, class Src>
typename std::enable_if<
  std::is_convertible<Src, const char*>::value
  && detail::IsSomeString<Tgt>::value>::type
toAppend(Src value, Tgt * result) {
  // Treat null pointers like an empty string, as in:
  // operator<<(std::ostream&, const char*).
  const char* c = value;
  if (c) {
    result->append(value);
  }
}

函数何时应该使用cstrings而不是字符串?他们为什么不编写函数来通过引用获取std :: string,因此可以像这样调用函数:

toAppend(" is ", 2, " point ", 5, str);

我唯一的猜测是效率,但是将std :: string转换为cstring比传递std :: string的引用更有效吗?也许cstring的实际操作比调用std :: string成员函数更快?或者也许这样一些人可以调用函数,如果他们只有一个cstring开头?嗯

1 个答案:

答案 0 :(得分:2)

这只是一个常见的约定,旨在强调最后一个参数是输出的事实。通常,最好使用引用而不是指针来定义参数,因为引用保证不为null,但有些人喜欢在调用函数时看到&来提醒自己参数是输出。