It is not only unnecessary but it is plain wrong in that place.
Consider what happens when you remove the const
from the return type:
/*const*/ std::vector<mv::Item>& mv::Workloads::getItems() const
{
return const_cast<std::vector<Item>&>(items_);
}
Now the method returns a non-const reference to a const
object! Note that the method itself is declared as const
, hence this
is const
in the context of this method and also items_
is const
. Using the reference returned by that method would lead to undefined behaviour when the method is called on a const test
instance.
In that sense, the only effect of the const_cast
here is to potentially silence an important compiler error should you ever decide to change the return type.
On the other hand, in the method as is (ie returning a const
reference) there is no reason for the cast. items_
is const
and a const
reference to it is returned.
const_cast
is useful eg to avoid code duplication for const
and non-const
methods when you do know for sure that the object you cast const
away really is not const
, see here for details.
PS: in case you actually do want to return a mutable reference to a member from a const
method, you would declare the member mutable
. Also then no const_cast
would be required. Though, mutable
should be used with care and usually isnt needed in the first place.