Re: Is there a proposal to fix the operator[] (rvalue/lvalue issues)??
SuperKoko wrote:
jose.diego@gmail.com wrote:
peter koch wrote:
Another interpretation is how operator[] works on constant maps:
#include <map>
int main()
{
const map<int,int> test;
return test[0];
}
Is this program ill-formed or will it return 0? I havent got the
standard in my hands, but my implementation tells me it is ill-formed.
But my gut feeling is that this should be well-formed and legal.
(Well... why shouldn't it?)
I think it is a major defect in std::map.
It should return 0, of course - a temporary
map::value_type::second_type()
I would not want to have an "operator[] const" having a different
semantic than "operator[]"
Actually, "operator[]" does modify the std::map, since it inserts the
key/value pair if it doesn't exist yet.
It could not be possible to say that operator[] doesn't modify the
std::map and just returns a map::value_type::second_type by value,
because it would not be a lvalue designating the value inside the
object, as would be expected (moreover, breaking actual code is not a
good idea).
But giving a different semantic to operator[] const is really a bad
idea.
Technically, the semantics of an exception-throwing, const operator[]
for std::map would be the same as the non-const version. But viewed in
terms of a design by contract, the criticism is valid: the
post-conditions and pre-conditions of the two operators[] would differ
significantly.
So after further reflection, I can now see how returning a
default-initialized value for a missing key would be a better choice
for a std::map const operator[] than would having it throw an
exception. After all, if the program really cared whether the key
exists in the map before attempting to retrieve its value with the
index operator - then the program would not be using the index operator
in the first place. And if a program does not care whether the key is
present in a non-const std::map, then there is little reason to expect
that would it care in the case of a const std::map to any greater
extent.
Greg
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]