【发布时间】:2010-01-31 18:13:28
【问题描述】:
来自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 类。
【问题讨论】:
-
我喜欢这个作为一个理论想法。我想知道如果没有“培训”,在实践中会有多混乱。
-
旧帖子,但对于未来的读者应该注意它已被提议:open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3442.html