Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

const_cast vs mutable and undefined behavior

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading