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.