Re: An interesting blog
- From: "Dennis \(Icarus\)" <nojunkmail@xxxxxxxxxxxx>
- Date: Sun, 25 Jul 2010 08:17:43 -0500
"jacob navia" <jacob@xxxxxxxxxxxx> wrote in message news:i2fm7j$vet$1@xxxxxxxxxxxxxxxxxxxx
http://apenwarr.ca/log/?m=201007#22
<quote>
Okay, one more example of C++ terribleness. This one is actually a tricky one, so I can almost forgive the C++ guys for not thinking up the "right" solution. But it came up again for me the other day, so I'll rant about it too: dictionary item assignment.
What happens when you have, say, a std::map of std::string and you do m[5] = "chicken"? Moreover, what happens if there is no m[5] and you do std::string x = m[5]?
Answer: m[5] "autovivifies" a new, empty string and stores it in location 5. Then it returns a reference to that location, which in the first example, you reassign using std::string::operator=. In the second example, the autovivified string is copied to x - and left happily floating around, empty, in m[5].
Ha ha! In what universe are these semantics reasonable? In what rational
Mine, and likely several others :-)
set of rules does the right-hand-side of an assignment statement get modified by default? Maybe I'm crazy - no, that's not it - but when I write m[5] and there's no m[5], I think there are only two things that are okay to happen. Either m[5] returns NULL (a passive indicator that there is no m[5], like you'd expect from C) or m[5] throws an exception (an aggressive indicator that there is no m[5], like you'd see in python).
How about foo(m[5]) Same thing right? m[5] is being assigned/copied/rererenced to the first argument of foo. Thart won't be helped by defining a new operator. If you want the object created in that case, but not for assignment, why?
Just use find and de-reference the iterator. the de-reference of the iterator when it's m.end() may indeed throw an exception
It's a shortcut for insert, except that it provides immediate access to the mapped item.
If you don't like the semantics of std::map[] operator......don't....use.....it.
Dennis
.
- Follow-Ups:
- Re: An interesting blog
- From: jacob navia
- Re: An interesting blog
- References:
- An interesting blog
- From: jacob navia
- An interesting blog
- Prev by Date: Re: GTK and images
- Next by Date: what happens when return 0?
- Previous by thread: Re: An interesting blog
- Next by thread: Re: An interesting blog
- Index(es):
Relevant Pages
|