以后可以使用分配器构造 std::tuple 的元素吗?
Possibility to construct std::tuple's elements later with an allocator?
据
我所知,将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::string
或std::vector<...>
的内存。
如果你想延迟对象的构造,你需要使用类似"可选"对象的东西,它会用标志指示它还没有被构造。相应类的实现策略将是围绕合适union
的包装器。
相关文章:
- std::tuple默认构造函数,带有move可构造元素
- 如何在std :: tuple中的每个元素上应用constexpr函数
- 使用派生自 'std::tuple' 的元素在 'std::tuple' 上调用 'std::get' - 格式不正确
- std::tuple的实现是否允许在触发空类元素的派生到基转换时失败
- std::map<tuple<int,int>.lower_bound/upper_bound 前缀搜索,而不找到后缀的最小/最大元素
- 在运行时按索引访问 std::tuple 元素的最佳方法
- 以后可以使用分配器构造 std::tuple 的元素吗?
- 如何创建具有指定数量的元素(相同类型)的 boost::tuple
- void * 到 std::tuple 在运行时的第 n 个元素
- 将std::pair转换为具有任意数量元素的std::tuple
- 以自然(非反向)顺序将func应用于std::tuple中的元素
- 为什么 libstdc++ 以相反的顺序存储 std::tuple 元素
- 如何在编译时不知道时从 std::tuple 获取第 i 个元素?
- 访问boost::fusion::tuple中的第0个元素
- 如何通过索引设置std::tuple元素
- 对于boost::hana::tuple,元素访问的时间复杂度是多少?
- 如何获取对 std::tuple 元素的引用
- 无法使用 boost::bind 来访问 boost::tuple 元素
- 为什么我不能使用 std::find 当容器中的基本元素是 boost::tuple 时
- 如何向Boost.Tuple中添加元素