C++ becoming usable

Recently I had to write a small project in C++ which involved a lot of cursing, since C++ has many awkward places and no sane way to get around them. Then I discovered that the GCC installed had C++0x support if you compile with “-std=c++0x” and suddenly C++ became a usable language for me.

And these are the core problems currently existing in C++, which C++0x solves:

Broken array data type

currently one has only the C arrays available which are nice if you want raw access to memory, but already fail if you just want to know the size of the array:

// ok you can do
int a[3];
cout << sizeof(a)/sizeof(int) << endl; // 3

// but this one fails
int a[3][2];
cout << sizeof(a)/sizeof(int) << endl; // 6 and no easy way to get the size of the first dimension

but with C++0x one has a proper array data type:

array<int, 3> a;
cout << a.size() // already more readable

array<array<int, 2>, 3> a;
cout << a.size() << endl; // 3

Manual Memory Management

currently one has only auto_ptr for memory management, but it is quite limited since there can be only one auto_ptr pointing to an object at any time. Coming with C++0x there will be a shared_ptr which can be copied around and assigned just like an ordinary pointer, but automatically realeases the memory.

// so if you always do
shared_ptr<int> p = new int;

// instead of
int* p = new int;

you will get reference counted garbage collection in C++. If you are coming from Java, you might winkle your nose, since this is not as efficient as the “proper” garbage collector in Java, but this is what is used in GTK and Python all the time…

Bad Collection Integration

although C++ already offers some Collection types besides of plain C arrays they are badly integrated in the language

// for instance this works
int a[3] = {1, 2, 3};

// but this does not
vector<int> a = {1, 2, 3};

well with C++0x the latter example also works 🙂

then there is also better integration with iterators

list<int> l;
// while you currently have to write
for (list<int>::iterator it = l.begin(); it != l.end(); it++) {
    cout << *it << endl;
}

// you will be able to write
for(int& i: l) {
    cout << i << endl;
}

Sugar on top

do you know the occasions where you have to write

list<vector<int>>* l = new list<vector<int>>();

// well now you can write
auto l = new list<vector<int>>();

this also helps in cases where you just do not care of the type or do not know it like in

auto f = bind(&Class::method, inst, "hello", _1, _2);
f(12, 13); // calls inst.method("hello", 12, 13)

Conclusion

this were only a few of the changes, but they already bring a new level of abstraction to C++, which allow expressing algorithms in a higher and more understandable level. This probably will not convert any Java programmers, but it will certainly make life for C++ alternatives like D harder, since they are certainly less attractive now.

Exit mobile version
%%footer%%