Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is const_casting a mutable field safe?

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.

like image 592
Lightness Races in Orbit Avatar asked Feb 18 '23 11:02

Lightness Races in Orbit


1 Answers

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.

like image 137
Tavian Barnes Avatar answered Feb 27 '23 09:02

Tavian Barnes