If allocators are stateless in C++, why are functions not used to allocate memory instead?
Asked Answered
A

2

5

The default std::allocator class is stateless in C++. This means any instance of an std::allocator can deallocate memory allocated by another std::allocator instance. What is then the point of having instances of allocators to allocate memory?

For instance, why is memory allocated like this:

allocator<T> alloc, alloc2;

T* buffer = alloc.allocate(42); 
alloc2.deallocate(buffer);

When functions could easily do that same job:

T* buffer = allocate(42);
deallocate(buffer);
Aglimmer answered 21/11, 2022 at 3:6 Comment(2)
E.g. you might want an allocator to hold an internal buffer of fixed size to allocate from. Not all allocators used in real life are default ones.Unlawful
It is possible to implement allocators that are stateful, and (if you follow requirements) use them in standard containers. Using objects as allocators allows the option of providing different allocation and deallocation schemes from the default. It's harder to do that with functions.Bayreuth
C
5

The default allocator is stateless, but other allocators may not be. However all allocators should share the same interface.

You are not supposed to use std::allocator directly as in your example. You can just use new and delete for direct allocation/deallocation.

You use std::allocator indirectly for generic allocator-aware types, such as containers, that should be agnostic to how the memory they use is allcoated. They usually have a template parameter for the allocator type satisfying the Allocator requirements/interface and std::allocator is typically the default argument for this template parameter.

And even in these cases you should use the allocator through std::allocator_traits, not by directly calling member functions of the allocator type, since many of them are defaulted through std::allocator_traits.

Charybdis answered 21/11, 2022 at 3:21 Comment(0)
D
1

? The default allocator class is stateless in C++. This means any instance of an allocator can deallocate memory allocated by another allocator instance.

No, that means any instance of std::allocator can deallocate memory allocated by another instance of std::allocator.

That says nothing about any type A which fits the rules of Allocators. std::allocator is stateless; allocators in general do not have to be.

Dimorph answered 21/11, 2022 at 3:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.