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;
}
So, frequently, you can pass string_view by reference and get away with it. But you should pass string_view by value, so that the compiler doesn't have to do those heroics on your behalf. And so that your code-reviewer doesn't have to burn brain cells pondering your unidiomatic decision to pass by reference.
Conceptually, string_view is only a view of the string and cannot be used to modify the actual string. When a string_view is created, there's no need to copy the data (unlike when you create a copy of a string). Furthermore, in terms of size on the heap, string_view is smaller than std::string .
Unfortunately, std::string_view doesn't have constructor taking const char (&) [N] but only (related to const char* ) const char* or const char*, std::size_t size .
Unlike C-style strings and std::string , std::string_view doesn't use null terminators to mark the end of the string. Rather, it knows where the string ends because it keeps track of its length.
static_cast<std::string>(sv)
is calling the std::string::string
constructor that expects any type convertible to std::string_view
(more details). Therefore, yes, it's still creating a brand new std::string
object, which in turn guarantees a null-terminated char sequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With