Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it legal to static_cast a string_view to a string

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 a const 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:

  1. Does this constructs a new string?

  2. 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;
}
like image 261
JohnKoch Avatar asked Jan 16 '19 06:01

JohnKoch


People also ask

Should I pass string_view by reference?

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.

What is the difference between string and string_view?

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 .

Can string_view be const?

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 .

Is string_view null terminated?

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.


1 Answers

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.

like image 166
Mário Feroldi Avatar answered Oct 05 '22 06:10

Mário Feroldi