I know that casting away const
-ness should be done with care, and any attempt to remove const
-ness from an initially const
object followed by modifying the object results in undefined behaviour. What if we want to remove const
-ness so that we may invoke a non-const function which doesn't modify the object? I know that we should actually mark such function const
, but suppose I'm using a "bad" code that doesn't have the const
version available.
So, to summarize, is the code below "safe"? My guess is that as long as you don't end up modifying the object you're ok, but I'm not 100% sure.
#include <iostream>
struct Foo
{
void f() // doesn't modify the instance, although is not marked const
{
std::cout << "Foo::f()" << std::endl;
}
};
int main()
{
const Foo foo;
const_cast<Foo&>(foo).f(); // is this safe?
}