- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
来自 StringPiece class in Chromium's source code 的文档:
// A string-like object that points to a sized piece of memory.
//
// Functions or methods may use const StringPiece& parameters to accept either
// a "const char*" or a "string" value that will be implicitly converted to
// a StringPiece.
//
// Systematic usage of StringPiece is encouraged as it will reduce unnecessary
// conversions from "const char*" to "string" and back again.
使用示例:
void foo(StringPiece const & str) // Pass by ref. is probably not needed
{
// str has same interface of const std::string
}
int main()
{
string bar("bar");
foo(bar); // OK, no mem. alloc.
// No mem. alloc. either, would be if arg. of "foo" was std::string
foo("baz");
}
这似乎是一个如此重要且明显的优化,以至于我无法理解为什么它没有得到更广泛的应用,以及为什么类似于 StringPiece 的类还没有在标准中。
我有什么理由不应该用这个类替换我自己的代码中使用的 string
和 char*
参数? C++ 标准库中是否已经存在类似的东西?
更新。我了解到 LLVM 的源代码使用了类似的概念:StringRef类(class)。
最佳答案
稍晚一点,但是...
StringPiece 背后的想法非常好。该类可以同时捕获 std::string
和 const char *
并将它们传递给函数。这是一个例子:
void process(const StringRef s){
// do something
}
process("Hello"); // const char *
std::string s = "Hello";
process(s); // std::string
process(std::string("Hello")); // std::string rvalue
如果函数接受 std::string
如果您传递 const char *
并且整个 char 被复制(例如使用 memcpy
)。
你也不需要担心 livetime,因为你将 StringRef
传递给函数/方法。
有这样的类:
Google - StringPiece
boost - boost::string_ref
LLVM - 字符串引用
我自己的(不完整的)实现可以在这里看到:
https://github.com/nmmmnu/HM3/blob/master/include/stringref.h
2016 年更新:
在 C++17 中,有 std::string_view
。我没有详细研究它,但总的来说它具有相同的想法。也类似于我的实现,它具有 constexpr
c-tor,因此您可以在编译时创建对象并将其与其他 constexpr
函数一起使用。
关于c++ - StringPiece/StringRef 习语不受欢迎有什么原因吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2172726/
来自 StringPiece class in Chromium's source code 的文档: // A string-like object that points to a sized p
我是一名优秀的程序员,十分优秀!