c++ - 返回对 std::function-wrapped lambda 中静态变量的引用会导致段错误

标签 c++ lambda static

this question之后,我意识到 std::function 存在更基本的问题 - 具体来说,当返回 lambda 中的静态变量的引用时,我会遇到段错误,但仅当 lambda 为包装在 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;
}

segfault only occurs on g++ , clang++ 似乎两者都很好。哪个编译器是正确的?如果是 g++,为什么使用 std::function 不起作用。

我应该注意,无论 hello 是静态的还是本地的,然后通过引用或值捕获,行为都是相同的。

最佳答案

[]() { 返回你好; }[]() -> std::string { return hello; }(无引用)。

您的func返回临时的悬空指针(具有const string&)。

当您调用 UB 时,两个编译器都是正确的。

auto func = func_t{lambda}; 是正确的。

关于c++ - 返回对 std::function-wrapped lambda 中静态变量的引用会导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49316688/

相关文章:

java - 为什么HashMap中的Entry类在java中是静态的

c++ - 在 C++ 中循环不正确

c++ - 为什么隐含的 "lambda to function pointer conversion"禁止静态成员的 "by reference"捕获?

java - 如何使用 PowerMockito 在静态方法中模拟新类实例

c# - 锁定抽象类中的静态或实例变量

python - Lambda 或 functools.partial 用于延迟函数评估?

c++ - 阻塞 TCP 套接字 : “send()” return and error handling

c++ - 链接错误 : <LNK1120> <LNK2020> Implement one serialization data class in C++

c++ - C++应用程序中的非永久巨大外部数据存储

c++ - 内联 lambda 表达式导致编译器错误