Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string& vs boost::string_ref

Tags:

c++

c++11

boost

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 ?

like image 687
cuv Avatar asked Sep 01 '16 06:09

cuv


People also ask

What is an std::string?

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.

Is std::string the same as string?

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 .

Is there std::string in C?

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.

Should I use std::string?

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.


2 Answers

The use case for string_ref (or string_view in recent Boost and C++17) is for substring references.

The case where

  • the source string happens to be std::string
  • and the full length of a source string is referenced

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.

like image 159
sehe Avatar answered Oct 27 '22 05:10

sehe


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.

like image 32
piwi Avatar answered Oct 27 '22 06:10

piwi