Casting Method Constants
As a follow-up to my previous question ( Writing to a class member via const & ), it is also well defined and correct to drop a const-ness class member method like this?
class A
{
public:
A()
: a(5)
{
}
int run() const
{
std::cout << "a: " << a << std::endl;
int& x = (int&)a;
x = 17;
std::cout << "a: " << a << std::endl;
return 0;
}
private:
int a;
};
int main()
{
A program;
return program.run();
}
Output (tested with C ++ 14 on cpp.sh with -O0, -Wall, -Wextra and -Wpedantic):
a: 5
a: 17
If not, what part of the standard would I name for an explanation?
source to share
Yes, your code is valid, although not recommended, unless the instance of the object you are starting from is irrelevant const
(which is the case in your code is A program;
not a constant).
Removing const
-ness from an instance const
is UB (undefined) behavior. Removing const
-ness from the original instance const
cast from const
is well defined, see for example the documentation for const_cast
.
If you really need to change a member variable from a member function const
, consider it as mutable
. Otherwise, your current technique will result in UB when someone (by mistake) calls your member function on an instance const
.
source to share