Conversion to const char*
suggest changeUse std::string::c_str() to obtain a null-terminated const char*. The pointer remains valid until a non-const operation on the string invalidates it, and it must not outlive the string.
Since C++17, calling data() on a non-const string returns a modifiable char*. Code may modify the existing characters through this pointer, but must not write beyond size() or change the null terminator at data()[size()] to a non-null value. Before C++17, data() returns const char*.
In C++11 and later, &s[0] also points to contiguous writable character storage. Prefer s.data() in modern code because it expresses the intent directly. Calling s.front() on an empty string is undefined behavior.
std::string str("This is a string.");
const char* cstr = str.c_str(); // cstr points to: "This is a string.\0"
const char* data = str.data(); // data points to: "This is a string.\0"
// Copy the contents of str to untie lifetime from the std::string object
std::unique_ptr<char[]> copy = std::make_unique<char[]>(str.size() + 1);
// Alternative to the line above (no exception safety):
// char* cstr_unsafe = new char[str.size() + 1];
std::copy(str.data(), str.data() + str.size(), copy.get());
copy[str.size()] = '\0'; // Add a null terminator.
// delete[] cstr_unsafe;
std::cout << copy.get();
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents