简体   繁体   中英

How can I test whether an allocator is using std::allocate for memory allocation?

I want to provide specialized optimizations for allocations done with std::allocator , but if someone has subclassed it without overriding allocate or deallocate , then I don't know how to detect whether they're still using std::allocator or not.

How do I do this?

Assuming they haven't defined their own allocate and deallocate functions, then one way to test is by testing the value

is_default_allocator_allocation<allocator_type>::value

to test whether the allocate and deallocate methods are the default ones.

If they have provided their own functions, then there is no generic way to test.

This solution does not look at the other methods.
It can give you occasional false negatives, but should not give false positives.

My implementation:

template<class Ax> char (&is_default_deallocate(void (std::allocator<typename Ax::value_type>::*)(typename Ax::pointer, typename Ax::size_type)))[1];
template<class Ax> char (&is_default_deallocate(void (Ax::*)(typename Ax::pointer, typename Ax::size_type)))[2];
template<class Ax> char (&is_default_allocate(typename Ax::pointer (std::allocator<typename Ax::value_type>::*)(typename Ax::size_type, void const *)))[1];
template<class Ax> char (&is_default_allocate(typename Ax::pointer (Ax::*)(typename Ax::size_type, void const *)))[2];

template<class Ax>
struct is_default_allocator_allocation  // tests allocate() and deallocate()
{
    static bool const value =
        sizeof(is_default_deallocate<Ax>(&Ax::deallocate)) == sizeof(char)
        && sizeof(is_default_allocate<Ax>(&Ax::allocate)) == sizeof(char);
};

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