[haiku-development] Re: QT for R2

Le Thu, 22 Mar 2012 23:07:16 +0100, Axel Dörfler <axeld@xxxxxxxxxxxxxxxx> a écrit:

The STL is certainly a bit flawed. Besides its ugly API, the iterators are very inconvenient to use in certain use cases (like removing an item). Have a look at its Java counterparts to see how its done right. I wouldn't mind to see such classes as part of the Haiku API.

I don't really see what's more "right" in Java.

Java : http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html
C++ : http://cplusplus.com/reference/stl/vector/

So, we have in Java multiple methods that do exactly the same thing (add and addElement and insertElementAt, elementAt and get), and helper functions for converting to and from an array.

Ok, Java has a remove(Object) method to remove an object from the vector. Note this can't work in C++ because it is not a reference-based language. So this is a nice feature we can't replicate.
In C++/STL you have to do :

std::iterator it = vector.begin();
while(it != vector.end())
        if(*it == stuffToDelete) // or any other condition
                it = vector.erase(it);

This is not *that* inconvenient, I don't see how it is possible to make it simpler without losing flexibility on the condition, and I don't think the Java equivalent is much shorter. It allows using it.remove() instead of it = vector.erase(it), but that's about it ?

So, most of Java niceness comes from the fact that it uses garbage collecting and references, and avoids you the need to delete your objects. This has another range of problems, such as not knowing when finalize() will be called, if at all. C++ brings more flexibility by allowing pointers, references and plain objects in a vector (or other container). Of course, this comes with some syntax complexity, but I think it's worth it.


Other related posts: