std::basic_string
(the type from which std::string
is a specialization) always stores its own data. So when you write
std::string s = "Hello";
You're invoking Constructor (5) of the available constructors (emphasis mine)
constexpr basic_string( const CharT* s,
const Allocator& alloc = Allocator() );
...
Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s
. The length of the string is determined by the first null character.
Then when you write
s = "World";
You're invoking overload (3) of the assignment operators (emphasis mine)
constexpr basic_string& operator=( const CharT* s );
...
Replaces the contents with those of null-terminated character string pointed to by s
as if by assign(s, Traits::length(s))
So std::string
keeps an internal buffer separate from the two literal character arrays you've written in your code, and that internal buffer knows how to manage its resources when you overwrite or move the string value.
See also Rule of Three (well, Rule of Five since C++11) for tons of good information on how to manage resources in your own classes in the same way.