Creating a std::string from std::string_view

596 Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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.

0
On

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.