Consider the following C++03 program:
#include <iostream>
struct T
{
mutable int x;
T() : x(0) {}
};
void bar(int& x)
{
x = 42;
}
void foo(const T& t)
{
bar(const_cast<int&>(t.x));
}
int main()
{
T t;
foo(t);
std::cout << t.x << '\n';
}
It appears to work, but is it safe for sure?
I'm only modifying a mutable
field, but having stripped away its const
context entirely makes me nervous.
It is safe, but also unnecessary. Because of the mutable
, t.x
is already of type int&
. Your example program works fine if the cast is removed entirely.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With