The output of your program will depend on compiler.
Type of the expression *(s+1)
is string, so what you do with *(s+1) = * s
is: First, you try to cast *(s+1)
to a string, then you try to assign that string to *s
, which will call the copy constructor of that newly casted string.
When the string is not empty, the compiler may allocate more memory than what is needed to store *s
's data ("some_string"), and the copy function in string only runs through its real data ("some_string") which means it doesn't access any memory further than what was allocated by *s
.
But when the string is empty, the compiler doesn't allocate that much memory, which causes the segment fault error.
So the result of your program may depend on compiler, how they reserve data for std::basic_string
and how they store it.