Std::string vs llvm::StringRef

Among std::string and llvm::StringRef which one is preferred? Why have LLVM devs defined a custom string class while there was one already present in c++?
Thanks in Anticipation.

1 Like

StringRef is not a string class but a reference to a string. It does not allocate nor own the underlying data. In STL, the closest analogy would be std::string_view. References are useful when we don’t want to transfer the ownership of the string data or copy it. Furthermore, StringRef can point to a memory buffer with string-like data that is not an std::string.

1 Like
void foo(std::string a) {}
void foo(const char *a) {}
void foo(llvm::StringRef a) {}
void foo(std::string_view a) {}

The first one will do a memory allocation to copy the string. The last three are semantically the same. The difference is style and different C++ standards.

1 Like