以后可以使用分配器构造 std::tuple 的元素吗?

Possibility to construct std::tuple's elements later with an allocator?

本文关键字:tuple 元素 std 可以使 分配器      更新时间:2023-10-16

我所知,将C++的分配器用于我自己的容器的一个原因是我可以分离分配和构造。

现在,我

想知道这是否可能通过以下方式用于 std::tuples:每次我构造一个 std::tuple,空间是保留的,但对象还没有被构造(还)。相反,我可以使用分配器来构造第 i 个参数,以便在需要时构造第 i 个参数。

伪代码:

struct my_struct {
    const bool b; // note that we can use const
    my_struct(int x) : b(x==42) {}
};
int main()
{
    std::tuple<int, my_struct> t;
    // the tuple knows an allocator named my_allocator here
    // this allocator will force the stack to reserve space for t,
    // but the contained objects are not constructed yet.
    my_allocator.construct(std::get<0>(t), 42);
    // this line just constructed the first object, which was an int
    my_allocator.construct(std::get<1>(t), std::get<0>(t));
    // this line just constructed the 2nd object
    // (with help of the 1st one
    return 0;
}

一个可能的问题是分配器通常绑定到一个类型,因此每个类型需要一个分配器。另一个问题是 std::tuple 的内存是否必须在堆上分配,或者堆栈是否可以工作。对我来说两者都可以。

不过,有可能吗?或者如果没有,这可以用我自己编写的分配器来完成吗?

分配

器不会帮助你初始化对象:分配器的作用是提供原始的,即未初始化的内存。分配器可以与std::tuple<...>一起使用,以自定义分配方式,例如,std::stringstd::vector<...>的内存。

如果你想延迟对象的构造,你需要使用类似"可选"对象的东西,它会用标志指示它还没有被构造。相应类的实现策略将是围绕合适union的包装器。