Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use basic_ostringstream with stateful custom allocator?? (C++11)

Tags:

c++

c++11

According to cppreference, std::basic_ostringstream can be instantiated with a custom allocator. Since C++11, allocators are allowed to have state and my custom allocator class does have internal per-instance state (actually each allocator instance has a pointer to an instance of a MemPool class, to which it forwards all allocation requests). This is why my allocator type can't just simply be default-constructed and be expected to work because after all, where is it going to get the address of the MemPool instance it's supposed to use from?

Unfortunately, if you take a look at the constructor prototypes of std::basic_ostringstream, you can see that none of the supported constructors actually take an allocator instance! I'm pretty sure that std::basic_ostringstream will have to make some allocation(s) to construct its resulting string, and I really want it to use my allocator for those, but how is it going to do that if I have no way of telling it which specific MemPool instance to use??

Have I overlooked something here? I feel like I must have but I sure don't see how at the moment.

like image 285
antred Avatar asked May 30 '14 13:05

antred


2 Answers

It is possible that the resolution to the LWG defect #2210, which added allocator instances to the constructors of many standard library containers, was not sufficiently thorough and the streams were overlooked. Or perhaps it wasn't clear enough how to approach them. I would suggest filing a new library defect report (or perhaps asking first in std-discussion)

like image 157
Cubbi Avatar answered Dec 29 '22 22:12

Cubbi


You can pass a basic_string<C, T, A> object to the constructor, and I expect all implementations will copy the allocator from that string object (probably via a call to allocator_traits<A>::select_on_container_copy_construction()) but that isn't clearly specified by the standard, and probably should be.

like image 21
Jonathan Wakely Avatar answered Dec 29 '22 22:12

Jonathan Wakely