Given a string_view sv
and a string s(sv)
, does s
use the same char array internally as sv
? Is it safe to say that when s
is destroyed, sv
is still valid?
CodePudding user response:
Creating a std::string
object always copies (or moves, if it can) the string, and handles its own memory internally.
For your example, the strings handled by sv
and s
are totally different and separate.
CodePudding user response:
Just run this demonstration program.
#include <iostream>
#include <string>
#inc,lude <string_view>
int main()
{
const char *s = "Hello World!";
std::cout << "The address of the string literal is "
<< static_cast< const void * >( s ) << '\n';
std::string_view sv( s );
std::cout << "The address of the object of the type std::string_view is "
<< static_cast< const void * >( sv.data() ) << '\n';
std::string ss( sv );
std::cout << "The address of the string is "
<< static_cast< const void * >( ss.data() ) << '\n';
}
Its output might look like
The address of the string literal is 00694E6C
The address of the object of the type std::string_view is 00694E6C
The address of the string is 0133F7C0
As you can see the address of the string literal is the same as the address of the memory returned by the data member data
of the object of std::string_view
.
That is the class std::string_view
is just a wrapper around the underlined referenced object.
As for the class std::string
then it creates its one copy of a string usually stored in the allocated memory.
For example you may not change an object of the type std::string_view
but std::string
is designed specially that process stored strings.
The suffix view
in the class name std::string_view
means that you can only view the underlined object to which an object of the type std::string_view
refers.