Unable to use custom allocator with allocate_shared/make_shared

前端 未结 2 827
离开以前
离开以前 2021-01-04 23:55

In my C++11 program, I use shared_ptr for some objects which are actively created and deleted. It so happened that standard allocator with operat

2条回答
  •  花落未央
    2021-01-05 00:23

    Your custom allocator does not meet the C++ Allocator requirements.

    In particular, it does not support being rebound to allocate objects of a different type. Usually allocators are templates, parameterized on the type they allocate memory for. allocate_shared needs to rebind the allocator so it can allocate a block of memory of the appropriate size and type, it does not want to allocate an array of char objects.

    // MyAlloc is a correct allocator, since allocator_traits can be instantiated
    

    This is not a correct assumption. Instantiating allocator_traits does not instantiate all its members.

    Also, is it OK to use char as value_type for this particular allocator

    That makes your allocator an allocator of char, but allocate_shared needs an allocator of some_internal_type_defined_by_the_library and so it tries to use std::allocator_traits::rebind_alloc to get an allocator for that type, but your allocator does not support the rebind requirement.

    If your allocator is a template of the form MyAlloc then allocator_traits can determine how to rebind it to MyAlloc, otherwise the type MyAlloc::rebind::other needs to be valid.

    The C++ standard shows the following as an example of an allocator supporting the minimum requirements for a C++ Allocator type:

    
    template 
    struct SimpleAllocator {
      typedef Tp value_type;
      SimpleAllocator(ctor args);
      template  SimpleAllocator(const SimpleAllocator& other);
      Tp* allocate(std::size_t n);
      void deallocate(Tp* p, std::size_t n);
    };
    template 
    bool operator==(const SimpleAllocator&, const SimpleAllocator&);
    template 
    bool operator!=(const SimpleAllocator&, const SimpleAllocator&);
    

提交回复
热议问题