Reputation: 38163
I just had the following case:
std::map< int, std::string > mm;
mm[ 1 ] = 5;
std::cout << mm[1];
assert( mm.find( 1 ) != mm.end() );
This does NOT print anything and the assert
does NOT fail.
It appeared to be a typo, it must be mm[ 1 ] = '5';
. After I figured it out, I tried:
std::string s1( 5 );
std::string s2 = 5;
None if this compiles. What happens?
Upvotes: 2
Views: 152
Reputation: 38163
std::map::operator[]
first creates an element with type std::map::mapped_type
, then returns a reference to it.
So, what happens here is the following:
std::string
object is created and default-constructed;std::map
operator=
is called on this objectIn this case, std::string::operator=
is called.
And here comes the "magic" - there's an overloaded operator=
, taking char
as argument. Also, the number can be implicitly converted to char
. So, what actually happens is:
std::string s;
s = (char)5;
For example, this:
mm[ 1 ] = 65; // ASCII for 'A'
mm[ 2 ] = 98; // ASCII for 'b'
std::cout << m[ 11 ] << mm[ 2 ];
will print Ab
.
Upvotes: 7