design - C++ allocators_trait::construct: motivation, trade-offs in ignoring -
i'm wrestling pain being caused std::allocator_traits::construct
. in order container "conforming" user of allocator concept, needs use construct
rather placement new construct objects. sticky me. have class (class a) designed allocator aware, , @ point needs create instance of other class (class b) in allocated memory. problem class b implements construction of new object. if use placement new, wouldn't issue: handle allocation, pass b memory address, , b construct that. since construction needs performed via construct, need inject allocator type b, templating it, creates huge mess.
it's bad enough considering using placement new, , static asserting instance of allocator not have construct method (note static construct function calls instance method if exists, otherwise calls placement new). have never felt tiniest urge write construct method allocator. cost of making part of allocator concept seems high me; construction has gotten entangled allocation, allocators supposed separate them. justifies existence of construct/destruct? insight design decision, examples of real (not toy) use cases, or thoughts on gravity of electing use placement new appreciated.
there similar question; std::allocator construct/destroy vs. placement new/p->~t(). asked quite long time ago, , don't find answer accepted there sufficient. logging bit trite use case, , then: why allocator logging actual construction of objects? can log allocations , deallocations in allocate , deallocate, doesn't answer question in sense of: why construction made province of allocator in first place? i'm hoping find better answer; it's been quite few years , allocators has changed since (e.g. allocators being stateful since 11).
a few points:
there isn't std container concept. container requirements tables in standard there document containers specified standard.
if have container wants interact
std::allocator_traits<alloc>
, have assumealloc
conforms minimum c++11 allocator requirements , interact viastd::allocator_traits<alloc>
.you are not required call
std::allocator_traits<alloc>::construct
.you are forbidden calling
alloc::construct
because may not exist.the standard-specified containers required call
std::allocator_traits<alloc>::construct
container::value_type
, , forbidden usingstd::allocator_traits<alloc>::construct
on other types container may need construct (e.g. internal nodes).
why construct
included in "allocator concept" way in c++98?
probably because committee @ time felt ease dealing x86 near , far pointers -- problem no longer exists today.
that being said, std::scoped_allocator_adaptor
modern real-world example of allocator customizes both construct
, destroy
. detailed specification of customizations point towards latest c++1z working draft, n4567. spec not simple, , why i'm not attempting reproduce here.
Comments
Post a Comment