C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Pseudo const answer

From: Ell <ell_se_at_[hidden]>
Date: Thu, 20 Mar 2025 05:15:48 +0200
If you remove the requirement to enforce the logical-constness of the
function (which I don't think is feasible, or even well defined), you're
left with a "mutable (member) function": a function that can be called
on a const object, but during which the object is modifiable.

This doesn't sound unreasonable in itself, but an object that zigzags
between constness and non-constness sounds like it could have all sorts
of pitfalls (as it stands, it obviously violates the rule that you can't
modify a const object during its lifetime, but even if you took care of
that). For example, is the object only modifiable through lvalues
derived from `this`? Can an object be simultaneously const and non-const
at the same time on different threads?

In a sense, constructors and destructors are already "mutable
functions", and while much more restricted, I'm not completely sure if
they're technically free of these issues either. For example, does this
program contain undefined behavior (is there any sense in which
`i = 123` happens after the lifetime of `x` had started?):

    struct X {
        int i;

        X () {
            std::thread ([this] { i = 123; }).detach ();
        }
    };

    int main () {
        const X x;

        while (true) volatile int _ = 0;
    }

Received on 2025-03-20 03:15:58