创建std :: function,它返回带有函数成员值的variant。分段故障

谢尔盖·科列斯尼克(Sergey Kolesnik)

我正在编写一个包装器类,以将自定义结构成员变量包装为变量。给定对struct对象的引用,std :: function必须返回一个变体,该变体包含特定成员的值-最初是使用std :: function创建的。这意味着,我需要在函数创建时保存一个指向指定类成员的指针。

这段代码可以编译,但是当我尝试调用函数对象时,会出现分段错误。为什么会发生以及如何解决?

#include <functional>
#include <variant>

#include <iostream>

struct Foo
{
    int a,
    b;
    char c;
    double d,
    e;
};

template <typename Struct, typename ... VarTypes>
struct WrapMemberGet
{
    template <typename T>
    static std::function<std::variant<VarTypes...>(const Struct&)>
            WrapGet(T(Struct::*mem_ptr))
    {
                return [&](const Struct& s)
                {
                    return std::variant<VarTypes...>(s.*mem_ptr);
                };
    }
};

int main(int argc, const char **argv)
{
    Foo  f{4, 8, 15, 16, 23};

    auto get_a = WrapMemberGet<Foo, char, int ,double>::WrapGet(&Foo::a);
    std::variant<char, int, double> var = get_a(f); // this must hold int = 4


    return 0;
}
卡尔德

您的WrapGet函数按值获取指向成员函数的指针,并且在函数内部将其捕获为lambda内部的引用。这意味着在函数结束后,使用lambda内部的引用悬空并使用它调用UB。

为了避免它按值捕获它,而是在lambda中创建本地副本。

return [=](const Struct& s)
{
    return std::variant<VarTypes...>(s.*mem_ptr);
};

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

比较用std :: bind创建的std :: function

使用成员函数创建std :: function无法编译

创建没有复制构造函数的std :: vectors的std :: vector

从函数返回std :: variant

从函数应用程序创建std :: vector

为std :: vector <struct>创建getter函数

如何使用随机值创建std :: map

如何使用数组创建std :: function?

使用类成员函数创建 std::thread - 最佳实践

使用std :: function作为类成员创建回调

创建一个指向返回std :: pair的函数的成员函数指针

std :: function到可变参数成员函数,然后绑定可变参数模板参数

创建带有空字符串“”的std :: locale

创建带有任何参数的std :: functions的unordered_map?

在带有标题的类中创建 std::thread

从Lambda创建的std :: function的奇数返回行为(C ++)

我们不能从initializer_list创建std :: array,但是我们可以使用带有可变参数的辅助函数来创建它吗?

如何在不使用std :: function创建类实例的情况下使用成员函数?

如何在没有默认构造函数的情况下使用std :: transform创建std :: array

如何使用std :: stoi作为默认值创建std :: function作为方法参数?

无法在gcc中创建std :: pair的const成员

创建一个带有任何签名的“什么都不做”的std :: function`?

如何返回在 std::variant 的所有替代项中定义的成员,即使成员是不同的类型?

C ++-为std :: vector <double>创建新的构造函数吗?

使用工厂函数创建std :: shared_ptr

稍后通过调用Class构造函数创建std :: vector <Class>

模板类中的 std::function 给出对象创建错误

是否可以使用fill构造函数创建std :: vector <std :: unique_ptr <Bar >>?

使用std::vector 创建矩阵类,如何在构造函数中设置std::vector 的大小?