Edit: I edited the code here to not use pointers because there were too many unrelated comments about it
#include <iostream>
struct Foo {
Foo(const int a) : total(a) {}
int index = 0;
const int total;
};
struct Bar {
Bar(const int a) : total(a) {}
mutable int index = 0;
const int total;
};
int main() {
const Foo foo(3);
for (
;
foo.index < foo.total;
const_cast<Foo*>(&foo)->index++ // 1. Undefined behavior because foo is const
)
std::cout << "Foo " << foo.index << std::endl;
const Bar bar(3);
for (
;
bar.index < bar.total;
bar.index++ // 2. Not undefined behavior because of mutable?
)
std::cout << "Bar " << bar.index << std::endl;
return 0;
}
To the best of my knowledge the line labeled with // 1. Undefined behavior because foo is const is undefined behavior because foo is a const object and const_cast is being used to modify the object anyway
However I am uncertain if there is any possible undefined behavior related to the line labeled with // 2. Not undefined behavior because of mutable?. It essentially is achieving the same result by using mutable instead of const_cast
My question then is whether there are cases where a const object with mutable members can cause undefined behavior
>Solution :
A mutable field is never const and thus can never invoke UB with const_cast. It is not the same behavior because theoretically #1 could place index in rom