简体   繁体   中英

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:

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

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 throughstd::allocator_traits , not by directly calling member functions of the allocator type, since many of them are defaulted through std::allocator_traits .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM