I am writing a game in which each data object is displayed by a ControlView. When a ControlView is set to display the data object, it should not change it. I want to use const to enforce this convention . However, in response to user interaction with the ControlView later, the data may be modified. So a non-const pointer needs to be stored. I am wondering if this is accepted and correct usage of const_cast?. skeletal code below
class Data
{
int m_int;
public:
void add(int i) { m_int += i ; };
};
class ControlView
{
Data* m_data;
public:
void set_data(const Data* d) //this call should not change d
{
m_data=const_cast<Data*>(d); //cast needed to compile
};
void manipulate_data(int x)
{
m_data->add(x);
}
};
In this case, no, don’t use
const. If you do, you’re letting anyone pass aconstas a parameter, and may end up running into undefined behavior afterwards: