Generally speaking, casting a T const
to a T
with const_cast<>
is almost always unnecessary. This is because the constant object is being converted into a non-constant temporary, and this can be safely accomplished without a cast.
int const n; // n is a constant int
int x = n; // perfectly safe
This is true even if T
is a pointer type.
int * const n; // n is a constant pointer to an int
int * x = n; // perfectly safe
However, if you move the const
keyword to the front, it is no longer making the pointer type constant, but the type that is being pointed to constant. Thus, for our example above:
const int * n; // n is a pointer to a constant int
int * x = n // error, x is a pointer to an int
You can see that x
points to a something different than what n
points to, and so the initialization will fail. In this case, the initialization would require a const_cast<>
:
int * x = const_cast<int *>(n);
// cast away the const-ness that n is pointing to
You should only do this if you know that n
is actually modifyable (it may not be if the pointer is to actual read-only memory), or if you know that the user of x
will not actually try to modify the contents pointed to by n
.
For your example, you seem to believe your const
method should return a pointer to data held by your object in such a way that the data be modifiable by the caller. That is, since the n()
method is declared const
, it means the contents of the object being accessed should be considered constant. Thus, n_
is an array of constant int
, which will decay to a pointer to constant int
, but you want to return a pointer to int
.
If you intend n_
to be modifiable regardless of whether the object is being treated as constant, you can declare that intention with the use of mutable
. This will make n_
be treated as non-constant even if the containing object is const
, and it thus makes the const_cast
unnecessary.
class A
{
private:
mutable int n_[10];
public:
/* ... */
int* n() const
{
return n_;
}
};