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

标签 c++ c++11 allocator stdtuple

据我所知,为我自己的容器使用 C++ 的分配器的一个原因是我可以将分配和构建分开。

现在,我想知道这是否可以通过以下方式用于 std::tuple:每次构造 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;
}

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

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

最佳答案

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

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

关于c++ - 以后可以使用分配器构造 std::tuple 的元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20752268/

相关文章:

c++ - unordered_set 可以为节点和桶列表使用不同的分配器吗?

c++ - 如何循环写入 vector ?

c++ - 什么时候刷新 FILE?

c++ - 如何在 vscode 中禁用 C++17 可用的结构化绑定(bind)的警告?

c++ - move 语义和运算符重载

c++ - 与自定义对象一起使用 accumulate

c++ - 我们如何插入实时可用的 mongocxx 文档?

c++ - 确定升压变体中的最大 sizeof()

c++ - 使用基于动态/状态的分配器的 STL 实现?