Is it legal to static_cast a string_view to a string

  • A+

My question is motivated by this answer on stackoverflow, 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,


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


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.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: