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

950 Views Asked by At

As far as I understood it, one reason to use C++'s allocators for my own container would be that I can seperate allocation and construction.

Now, I wonder if this is possible for std::tuples in the following way: Each time I construct an std::tuple, the space is reserved, but the objects are not constructed (yet). Instead, I can use the allocator in order to construct the i-th argument just when I want to.

Pseudo-Code:

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;
}

One possible problem is that allocators are usually bound to a type, so I'd need one allocator per type. Another question is whether the memory for the std::tuple must be allocated on the heap, or if stack might work. Both is ok for me.

Still, is it possible somehow? Or if not, could this be done with an allocator I write my own?

1

There are 1 best solutions below

7
On

Allocators won't help you with initializing objects: the role of an allocator is to provide raw, i.e., uninitialized memory. The allocator could be used with a std::tuple<...> to customize how, e.g., memory for a std::string or a std::vector<...> is allocated.

If you want to delay construction of objects you'll need to use something like an "optional" object which would indicate with flag that it isn't constructed, yet. The implementation strategy for a corresponding class would be a wrapper around a suitable union.