The code:
1 2 3 4 5 6
|
int main() {
std::string foo( "Hello" );
foo[1] = 'u';
foo[3] = "u";
return 0;
}
|
Line 2:
Object foo is created in stack memory like any local variable. It is not const.
There is an array in non-modifiable memory that contains
{ 'H', 'e', 'l', 'l', 'o', 0 }
.
The address of 'H' is given to the constructor of foo. The constructor dynamically allocates yet another (modifiable) memory block (from Free Store) and copies characters from the const array.
Line 3:
The foo[1] returns a reference to the second
char
acter in the foo's dynamic memory block. The character 'u' is written (assigned) to that position. Thus, the foo has string "Hullo" after this statement.
Line 4:
The foo[1] returns a reference to the fourth
char
acter in the foo's dynamic memory block.
The "u", however, is a constant string literal, just like the "Hello" on line 2, and thus the assignment operator has a
const char *
(the address of the u) as its right operand and a
char
(reference to the second 'l' within foo) as the left operand.
The assignment operator does not know anything about string, it sees just a char and a pointer. There is no such assignment operator that would assign something from character pointer into a character. Thus, a syntax error.