0

An std::string_view is kind of a replacement for char* in C. It's a string that is not copied from place to place, just as char* is just a place in memory that is referenced from time to time.

However, sometimes we need to transform it in a string for functions that accept a string.

How do I do that?

Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150
  • @SergeyA If there's no answer to that on this site, I would not downvote this one. The `std::string` constructor is explicit, so beginners can be confused as why a string cannot be constructed with a string view without typing`std::string` to convert it. – Guillaume Racicot May 21 '21 at 20:17
  • 2
    @GuillaumeRacicot but there is :) – SergeyA May 21 '21 at 21:32

3 Answers3

8

std::string has constructors that will accept a std::string_view as input, eg:

std::string_view sv{...};
std::string s1{sv};
std::string s2{sv, index, length};

Alternatively, you can use the std::string constructor that accepts a char* and length as input, eg:

std::string_view sv{...};
std::string s1{sv.data(), sv.size()};
std::string s2{sv.data()+index, length};
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
6

A std::string as a constructor for that, but only an explicit one.

void f(std::string s);

std::string_view sv;
f(sv); // Error! Cannot convert implicitly
f(std::string{sv}); // Works fine.

This has been designed like this to prevent accidental memory allocations.

See documentation for std::basic_string::basic_string (10)

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
1

Just use std::string's constructor:

 std::string{my_string_view}
Guerlando OCs
  • 1,886
  • 9
  • 61
  • 150