【问题标题】:When should functions take cstrings instead of strings? (C++)函数什么时候应该使用 cstrings 而不是字符串? (C++)
【发布时间】:2012-06-07 17:47:59
【问题描述】:

所以我一直在探索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 开头,也许他们可以调用该函数?嗯

【问题讨论】:

  • 它接受 std::string* 而不是 std::string& 正如你所建议的。它不接受 const char*。在内部 std::string* std::string & 是相同的。参考文献通常是首选,但他们可能已经做到了一致性。

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


【解决方案1】:

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

【讨论】:

  • 这能回答问题吗?我认为问题是为什么是 C 字符串而不是 C++ 字符串,而不是为什么是指针而不是引用。
  • 答案是,他们没有把 C 字符串放在那里。他们正在获取指向 std::string 的指针。
猜你喜欢
  • 2012-08-20
  • 1970-01-01
  • 2011-09-29
  • 2010-12-11
  • 2013-04-24
  • 2011-11-18
  • 2021-12-06
  • 1970-01-01
  • 2010-10-13
相关资源
最近更新 更多