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

标签 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);

Inside 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 开头,也许有些人可以通过这种方式调用该函数?嗯嗯

最佳答案

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

关于c++ - 什么时候函数应该使用 cstrings 而不是字符串? (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10868014/

相关文章:

c++ - clang 3.9、auto_ptr 和 boost

string - 用空格分割字符串

php - 函数不返回值

c++ - 为什么不应该派生自 C++ std 字符串类?

c++ - 接受指针数组的输入

java - 在 Java 8 Stream 上执行操作时如何保留状态?

c - 如何在 C 中不使用指针的情况下通过函数传递 2D 数组

r - 如何在 Base 中生成 "Unbalanced"(不等)因子水平?

c++ - decltype(*this) 等效于外部函数体

python - 比较 numba 编译函数中的字符串