2

据我了解,将 C++ 的分配器用于我自己的容器的一个原因是我可以将分配和构造分开。

现在,我想知道 std::tuples 是否可以通过以下方式实现这一点:每次构造 std::tuple 时,都会保留空间,但还没有构造对象。相反,我可以使用分配器来在我想要的时候构造第 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 的内存是否必须在堆上分配,或者堆栈是否可以工作。两者对我来说都可以。

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

4

1 回答 1

1

分配器不会帮助您初始化对象:分配器的作用是提供原始的,即未初始化的内存。分配器可以与 a 一起使用std::tuple<...>来定制如何分配例如 astd::string或 astd::vector<...>的内存。

如果您想延迟对象的构建,您将需要使用类似于“可选”对象的东西,它会用标志指示它尚未构建。相应类的实现策略将是一个合适的union.

于 2013-12-23T22:48:43.947 回答