Tricky mistake

Author:Wojciech Muła
Added on:2015-05-25

A programmer wrote:

class container;

class IndexOutOfBounds {
public:
    IndexOutOfBounds(const std::string& msg);
};

void container::remove(int index) {

    if (index < 0 || index >= size()) {
        throw new IndexOutOfBounds("Invalid index: " + index);
    }

    // the rest of method
}

Do you see the mistake? The programmer thought that the expression "Invalid index: " + index evaluates to std::string("Invalid index: 5").

In fact the type of the expression "Invalid index: " is char[15], so char[15] + integer results in — more or less — char*. For index in range [0, 15] an exception will carry the tail of the message, for example when index=10 then message assigned to the exception object will be "dex: ". For indexes larger than 15 and less than 0 a program likely crash.

This is why I hate C++, this language has many dark corner, stupid conventions, implicit conversion and not mention UB ("just" 150 UB, if you're curious).