Note for string compatible type conversion in C++

Type conversion can be the most googled material in daily programming regardless of the kind of language. That is also the case when writing C++ code. For example, I often forget how to convert the std::string to char * and vice versa. llvm::StringRef brings additional complexity definitely into this conversion graph between string compatible types in C++.

This article is a brief note on how to move back and forward among these three data types so that we can later refer to them as necessary.

std::string -> char *

It’s pretty simple. std::string has a method to return the pointer to the underlying character entities. c_str() allows us to do so.

std::string str = "Hello, World";
const char *c = str.c_str();

char * -> std::string

std::string has a constructor that takes the const char* type. Thus, it enables you to create std::string from the char * type.

const char *c = "Hello, World";
std::string str(c);

llvm::StringRef -> std::string

llvm::StringRef has a method to return the string entity, str().

llvm::StringRef stringRef("Hello, World");
std::string str = stringRef.str();

llvm::StringRef -> char *

llvm::StringRef has a method to return the underlying data pointer. data() method will do that.

llvm::StringRef stringRef("Hello, World");
const char *c = stringRef.data();
llvm::StringRef stringRef("Hello, World");
std::string str = stringRef.str();

std::string, char * -> llvm::StringRef

We can construct llvm::StringRef from both types of std::string and char * by its constructor.

std::string str = "Hello, String";
const char *c = "Hello, Char";
llvm::StringRef stringRef1(str);
llvm::StringRef stringRef2(c);

Reference