My question is motivated by this answer on stackoverflow, https://stackoverflow.com/a/48082010/5360439. To quote,
Q: How you convert a
std::string_view
to aconst char*
?A: Simply do a
std::string(string_view_object).c_str()
to get a guaranteed null-terminated temporary copy (and clean it up at the end of the line).
Unfortunately, it constructs a new string
. I am wondering if it is OK to simply do,
static_cast<string>(string_view_object).c_str()
Now, my question is:
Does this constructs a new string?
Is it guaranteed to return a null-terminated char sequence?
I have a small piece of code for demonstration. It seems to work fine. (See wandbox results)
#include <string>
#include <iostream>
#include <string_view>
#include <cstring>
int main()
{
std::string str{"0123456789"};
std::string_view sv(str.c_str(), 5);
std::cout << sv << std::endl;
std::cout << static_cast<std::string>(sv) << std::endl;
std::cout << strlen(static_cast<std::string>(sv).c_str()) << std::endl;
}