To convert a std::string_view
back to a std::string
, you need to create a new std::string
object and pass the std::string_view
to its constructor.
This is necessary because std::string_view
provides a view over a string without owning the data, while std::string
owns and manages the data.
Here's an example:
#include <iostream>
#include <string>
#include <string_view>
int main() {
std::string_view view{"Hello, world"};
std::string str{view};
std::cout << str;
}
Hello, world
In this example, std::string str{view};
constructs a new std::string
by copying the data from the std::string_view
. This way, str
owns its data, and you can modify it independently of the original view.
Remember, constructing a std::string
from a std::string_view
involves copying the data, which can be expensive for large strings. Always consider the performance implications in your specific use case.
Answers to questions are automatically generated and may not have been reviewed.
A practical introduction to string views, and why they should be the main way we pass strings to functions