I just came across this code fragment, but I do not understand how it compiles:
class temp {
int value1;
mutable int value2;
public:
void fun(int val) const
{
((temp*) this)->value1 = 10;
value2 = 10;
}
};
What is the meaning of this line
((temp*) this)->value1 = 10;
value1
is getting assigned to 10, without any error. But value1
is not mutable
. How does this compile?
When a member variable does not have the mutable
qualifier, you cannot modify it when an object is const
.
When a member variable has the mutable
qualifier, you can modify it even when an object is const
.
Simple example:
struct Foo
{
int var1;
mutable int var2;
};
const Foo f{};
f.var1 = 10; // Not OK
f.var2 = 20; // OK
When you have:
void fun(int val) const
{
((temp*) this)->value1 = 10;
value2 = 10;
}
you are bypassing the const
-ness of the object and changing it in a way that you are not supposed to. This is subject to undefined behavior.
As far as the compiler is concerned, that code is equivalent to:
void fun(int val) const
{
temp* ptr = (temp*)this
// The compiler does not know how you got ptr.
// It is able to modify value1 through ptr since ptr
// points to a non-const object.
ptr->value1 = 10;
value2 = 10;
}
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