Does it matter anymore if I use boost::string_ref
over std::string&
? I mean, is it really more efficient to use boost::string_ref
over the std version when you are processing strings ? I don't really get the explanation offered here: http://www.boost.org/doc/libs/1_61_0/libs/utility/doc/html/string_ref.html . What really confuses me is the fact that std::string
is also a handle class that only points to the allocated memory, and since c++11, with move semantics the copy operations noted in the article above are not going to happen. So, which one is more efficient ?
std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.
There is no functionality difference between string and std::string because they're the same type. That said, there are times where you would prefer std::string over string .
The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.
Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one. Save this answer.
The use case for string_ref
(or string_view
in recent Boost and C++17) is for substring references.
The case where
std::string
is a (a-typical) special case, where it does indeed resemble std::string const&
.
Note also that operations on string_ref
(like sref.substring(...)
) automatically return more string_ref
objects, instead of allocating a new std::string
.
I have never used it be it seems to me that its purpose is to provide an interface similar to std::string
but without having to allocate a string for manipulation. Take the example given extract_part()
: it is given a hard-coded C array "ABCDEFG"
, but because the initial function takes a std::string
an allocation takes place (std::string
will have its own version of "ABCDEFG"
). Using string_ref
, no allocation occurs, it uses the reference to the initial "ABCDEFG"
. The constraint is that the string is read-only.
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