22 Jul 2010 redi   » (Master)

apenwarr's repeated suggestion for operator[]= is silly, that only helps types which have an operator[].

A better, more general solution is already in C++0x: Move Semantics. That removes performance overheads that copy elision (e.g. RVO) can't help with, in all sorts of situations, not just Avery's specific one for std::map.

And if you want the behaviour of python dictionaries, that's trivial:

template<typename Map, typename K>
typename Map::mapped_type&
get(Map& map, K&& key)
    auto pos = map.find(key);
    if (pos == map.end())
        throw std::runtime_error("Not found");
    return pos->second;

That works for anything with the same interface as std::map and allows get(m, 5) = "chicken" to work as you want, with no loss of efficiency*

The constructive criticism is valid, but years too late. C++0x has closures (which have zero overhead compared to a C function unless you need it, and can even be converted to C function pointers and passed to existing APIs,) it has typesafe varargs, and thanks to move semantics it can be significantly faster than C at copying data structures around, so there's no reason for functions to take out parameters by pointer/reference, just return them and watch the copies not happen. It also has type inference, and explicit conversion operators, which only convert when you want them to e.g. a smart pointer's conversion to bool happens if used in an if but not if you try to assign it to an int.

The bad parts of C++ may not have been removed, but some seriously good stuff has been added. (Edit: all of the above is available today in GCC.)

Oh, and exception handling is not too complicated. You must be doing it wrong.

* Actually a better version would use

typename Map::key_type key2(std::forward<K>(key));
for maximum efficiency in the case where K is not the same type as key_type and requires a conversion.

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!