unreachable-code In C++11, what may cause this?

Viewed 146

I wrote the following code in Clion for my C++11:

Matrix<T> &Matrix<T>::operator=(const Matrix<T> &matrix) {
    if (this == &matrix) {
        return *this;
    }
    int matrix_size = matrix.size();
    T *temp = new T[matrix_size];
    try {
        for (int i = 0; i < matrix_size; ++i) {
            temp[i] = data[i];
        }
    }
    catch (...)
    {
        delete[] temp;
        throw;
    }
    delete[] data;
    data = temp;
    dimensions = matrix.dimensions;
    return *this;
}

But it shows me that what's written inside catch is an unreachable-code, why is that?

1 Answers

Clion is probably wrong. It clearly isn't unreachable if T throws on copy assignment.

Demo

The only way I could see the assessment being correct is if it checks every instanciation of Matrix and makes sure, in each case, that the type used doesn't throw. However, I still wouldn't agree with it since Matrix could be used somewhere Clion doesn't have access to.

Note that you shouldn't code like this anyway. Use a std::vector instead of a raw pointer and dynamic allocations. Then you don't need the try-catch block: std::vector takes care of that for you.

Also, I believe you meant to write temp[i] = matrix.data[i]; in the loop.

Related