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

Time:11-21

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

CodePudding user response:

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.

CodePudding user response:

? 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.

  • Related