2

Following on from this question, I realised was having more fundamental problems with std::function - specifically I'm suffering segfaults when returning a reference to a static variable in lambda but only when the lambda is wrapped in a std::function:

#include <iostream>
#include <functional>

using namespace std::string_literals;

namespace
{
const auto hello = "Hello"s;
}

int main()
{
    using func_t = std::function<const std::string& ()>;

    auto lambda = []() -> const std::string& { return hello; };
    std::cout << lambda() << std::endl; // Fine

    auto func = func_t{[]() { return hello; }};
    std::cout << func() << std::endl;   // Bang!

    return EXIT_SUCCESS;
}

The segfault only occurs on g++, clang++ seems to be fine with both. Which compiler is correct? And if it is g++, why does using std::function not work.

I should note that the behaviour is the same whether or not hello is static, or local and then captured by reference or value.

cmannett85
  • 21,725
  • 8
  • 76
  • 119

1 Answers1

4

[]() { return hello; } is []() -> std::string { return hello; } (without reference).

Your func return dangling pointer of temporary (to have const string&).

Both compilers are correct as you invoke UB.

auto func = func_t{lambda}; would be correct.

Jarod42
  • 203,559
  • 14
  • 181
  • 302