Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

T* buffer = allocate(42);
deallocate(buffer);

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading