Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22268

Why does this C++ program capturing lambda argument by reference segfault?

$
0
0

Here is a minimal program that segfaults with gcc-8.3.0, compiled with -std=c++2a:

struct Command {
    double x;
};

template <typename T>
struct AutoBrake {
    AutoBrake(const T& publish) : publish{ publish } {}
    const T& publish;
};

int main()
{
    int count{};
    AutoBrake brake{ [&count](const Command&) {
        count += 1;
    } };

    brake.publish(Command{ 1.1f });
}

Debugging shows that it crashes when accessing the count reference inside the lambda expression when running brake.publish.

However if the command struct does not contain any fields, the program runs fine:

struct Command {};
...

AFAIK since Command is taken as a const reference, its lifetime should be extended to the end of main here, so it should not be a dangling reference to a temporary.

Moreover if I do not access count in the lambda the program does not segfault:

...
    int count{};
    AutoBrake brake{ [&count](const Command&) {} };
    brake.publish(Command{});
...

Finally, if I first store the lambda as a variable it does not segfault:

    int count{};
    auto func = [&count](const Command&) { count += 1; };
    AutoBrake brake{ func };
    brake.publish(Command{});

Viewing all articles
Browse latest Browse all 22268

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>