Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 什么时候函数应该使用cstring而不是字符串?(C+;+;)_C++_String_Function_C++11_Parameter Passing - Fatal编程技术网

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

C++ 什么时候函数应该使用cstring而不是字符串?(C+;+;),c++,string,function,c++11,parameter-passing,C++,String,Function,C++11,Parameter Passing,所以我一直在探索——Facebook的开源库,它们的大多数实用函数都使用cstring而不是字符串。他们为什么这样做?这些示例传入对std::string的引用,并隐式转换为cstring。下面是他们的一个函数示例,我想让这个问题重点关注: 函数的调用方式: // Multiple arguments are okay, too. Just put the pointer to string at the end. toAppend(" is ", 2, " point ", 5, &s

所以我一直在探索——Facebook的开源库,它们的大多数实用函数都使用cstring而不是字符串。他们为什么这样做?这些示例传入对std::string的引用,并隐式转换为cstring。下面是他们的一个函数示例,我想让这个问题重点关注:

函数的调用方式:

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

/**
* 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);
  }
}

我唯一的猜测是为了效率,但是将std::string转换为cstring是否比传递std::string的引用更有效?可能cstring的实际操作比调用std::string成员函数更快?或者,如果一开始只有一个cstring,那么也许有人可以通过这种方式调用该函数?hmmm

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

它接受std::string*而不是std::string&正如您所建议的那样。它不接受常量字符*。内部std::string*std::string&是相同的。推荐人通常是首选,但他们可能已经做到了。这是否回答了问题?我想问题是为什么C字符串而不是C++字符串,而不是指针为什么不是引用。答案是,他们不在那里使用C字符串。他们正在使用指向std::string的指针。
toAppend(" is ", 2, " point ", 5, str);