jeudi 26 mars 2020

Behavior difference of lambda function mutable capture from a reference to global variable

I found the results are different across compilers if I use a lambda to capture a reference to global variable with mutable keyword and then modify the value in the lambda function.

#include <stdio.h>
#include <functional>

int n = 100;

std::function<int()> f()
{
    int &m = n;
    return [m] () mutable -> int {
        m += 123;
        return m;
    };
}

int main()
{
    int x = n;
    int y = f()();
    int z = n;

    printf("%d %d %d\n", x, y, z);
    return 0;
}

Result from VS 2015 and GCC (g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609):

100 223 100

Result from clang++ (clang version 3.8.0-2ubuntu4 (tags/RELEASE_380/final)):

100 223 223

Why does this happen? Is this allowed by the C++ Standards?

Aucun commentaire:

Enregistrer un commentaire