Search code examples
c++constantsconst-cast

Is this a valid use of const_cast?


In the sample code, calling message() will never affect the contents of the class, so I'd like the method to be const. But I don't want the return value also to be const, so is it safe to use const_cast as below? or is there a better solution?

EDIT: Sorry.. so n_ is a pointer!

EDIT2: I finally managed to re-produce the problem correctly. What if n_ is an array as in int n[100]? Then I do see a problem without const_cast.

class A
{
private:
    int n_[10];

public:
    /* ... */

    int* n() const
    {
        return const_cast<int*>(n_);
    }
};

Solution

  • No, that is not a valid use of const_cast.

    Your function is not modifying the array, but it is granting rights to modify the array to the caller. As such, it should have those rights itself. You can't give someone access to something which you yourself don't have access. So the method should not be const, and the const cast is then unnecessary.

    You might also want a const version of the function, which returns a const int*. This is the same principle as, for example, std::vector::operator[]. Even though the operator doesn't modify the vector, it grants access to modify the vector, and so it is not a const function. (but there is also a const overloaded version, which returns a const reference, thereby not granting the right to modify the vector)