Is const_casting 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&>(tx)); } int main() { T t; foo(t); std::cout << tx << '\n'; } 

It works , but is it safe?

I only change the mutable field, but by removing its const context, I am completely nervous.

+4
source share
1 answer

It is safe, but also not necessary. Due to mutable , tx already has an int& type. Your sample program works fine if the cast is completely removed .

+8
source

Source: https://habr.com/ru/post/1446977/


All Articles