From the documentation of the 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.
Example of use:
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");
}
This seems like such an important and obvious optimization that I can't understand why it's not more widespread, and why a class similar to StringPiece is not already in the standard.
Are there any reasons why I shouldn't replace the use of string
and char*
parameters in my own code with this class? Is there anything like it already in the C++ standard libraries?
UPDATE. I've learnt that LLVM's source uses a similar concept: the StringRef class.
Bit later, but ...
Idea behind StringPiece is very good. The class can capture both std::string
and const char *
and pass them to a function. Here is an example:
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
If function accepted std::string
you actually creating a temporary object if you pass const char *
and whole char is copied (for example with memcpy
).
You also does not need to worry about livetime, because you are passing StringRef
to function / method.
There are such class in:
Google - StringPiece
boost - boost::string_ref
LLVM - StringRef
My own (incomplete) implementation can be seen here:
https://github.com/nmmmnu/HM3/blob/master/include/stringref.h
Update 2016:
In C++17, there are std::string_view
. I did not study it in details, but in general it has same idea. Also similar to mine implementation it have constexpr
c-tor, so you can create objects at compile time and use it along with other constexpr
functions.
The question has been very well answered already, but to give some more context, the StringPiece
pattern is very widely used internally at Google and has been for many years. It is strongly recommended in Google coding guidelines, which is almost surely why Chrome (and subsequently Chromium) have adopted it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With