Reputation: 399
I am trying to to understand const_cast
.
In the example below, items_
is a private member variable.
The method getItems()
is a const
method, which means that it cannot modify the member variable items_
.
getItems()
returns a const vector
reference which means that you cannot modify the member variable items_
.
My question is, is const_cast
necessary here? I don't think so as I don't need to cast away constness?
#include <iostream>
class test {
std::vector<Item> items_;
public:
const std::vector<Item>& getItems() const;
};
const std::vector<mv::Item>& mv::Workloads::getItems() const
{
return const_cast<std::vector<Item>&>(items_);
}
Upvotes: 1
Views: 230
Reputation: 122458
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.
Upvotes: 5
Reputation: 884
It is not neccessary, simply return the _items
.
Const member functions see the the object itself (*this
) as const, so every data member is seen as const, from which building and returning const reference is allowed.
#include <iostream>
using namespace std;
class test {
std::vector<Item> items_;
public:
const std::vector<Item>& getItems() const;
};
const std::vector<mv::Item>& mv::Workloads::getItems() const
{
return items_;
}
Upvotes: 3