据我了解,将 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 的内存是否必须在堆上分配,或者堆栈是否可以工作。两者对我来说都可以。
不过,有可能以某种方式吗?或者如果没有,这可以通过我自己编写的分配器来完成吗?