Is it legal to static_cast a string_view to a string

Viewed 4678

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;
}
2 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.

A simple way to check if static_cast<std::string>(sv) constructs a new string is to verify if it's able to change original string.

#include <string>
#include <iostream>
#include <string_view>
#include <cstring>

int main()
{
  std::string str{"0123456789"};
  std::string_view sv = str;

  std::cout << sv << std::endl;
  static_cast<std::string>(sv)[0] = 'a';
  std::cout << static_cast<std::string>(sv) << std::endl;
} 

sv remains unchanged, so it does creates a new string.

See results on wandbox.

Related