3

After watching You don't know const and mutable I am kind of puzzled how to handle mutable properly in future. While I think the case of const is pretty much safe, since one would assume physical read-only by default (minus the old logic exception), properly handling mutable puzzles me. For example with the new threadsafe-condition the following seems wrong:

int main() {
    int n;
    [=]() mutable {n = 10;}();
    return n;
}

I would assume, that in this case, n would have to be wrapped into a std::atomic or the copy of n be protected by concurrent writes in another way!?

7
  • Which n exactly are you talking about? The variable declared in main or the copy in the lambda?
    – Henrik
    Commented Jan 8, 2013 at 11:24
  • 1
    The new mutable condition only applies to explicitly marked objects, in this case the copy of n.
    – abergmeier
    Commented Jan 8, 2013 at 11:27
  • 2
    The mutable for a lambda is a different kind of mutable than the one for members. It just means that the member operator() is not marked as const.
    – Xeo
    Commented Jan 8, 2013 at 11:33
  • 4
    Yes, of course. §5.1.2/5: "This function call operator is declared const (9.3.1) if and only if the lambda-expression’s parameter-declaration-clause is not followed by mutable."
    – Xeo
    Commented Jan 8, 2013 at 12:10
  • 2
    @LCIDFire A "confilcting example" to the language standard? Most probably not, and if yes, then that's a bug in the implementation! Commented Jan 9, 2013 at 12:39

1 Answer 1

1

It may be clearer to you if we wrote the lambda out explicitly:

struct mylambda
{
    mylambda(int n) : n(n) {}

    void operator()() /* const <- lambda specified as mutable, operator not const */
    {
        n = 10;
    }

private:
    int n;
};

int main() {
    int n = 0;
    mylambda(n)();
    return n;
}

(Side note: you actually have undefined behavior in your example because when your lambda copies n, it's reading from an uninitialized variable. I've initialized it here to fix that small error.)

As you can see, you have no mutable members so nothing needs to be changed to be thread-safe (according to the talk). Just a regular member variable that can change through a non-const member function; non-const member functions are not assumed to be thread-safe.

I don't know if you can mark the lambda member as mutable; if you could, you could be in a position where thread safety is a concern (coupled with a const function call operator). But I don't think it's possible.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.