std :: allocator <void>的弃用

Lin*_*gxi 12 c++ memory-management allocator c++-standard-library c++17

相关:为什么标准容器需要allocator_type :: value_type作为元素类型?

据说自C++ 17以来已经弃用了以下内容:

template<>
struct allocator<void>;
Run Code Online (Sandbox Code Playgroud)

我想知道它是否已被弃用,因为现在只能使用主模板allocator<void>,或者allocator<void>不推荐使用用例.

如果是后者,我想知道为什么.我认为allocator<void>在指定未绑定到特定类型的分配器时非常有用(所以只需要一些模式/元数据).

sp2*_*nny 5

根据p0174r0

类似地,std::allocator<void>定义了各种模板重新绑定技巧可以在原始 C++98 库中工作,但它不是一个实际的分配器,因为它缺少allocatedeallocate 成员函数,默认情况下不能从 allocator_traits. 随着 C++11 和allocator_traits 中的void_pointer 和类型别名的出现,这种需求就消失了。const_void_pointer但是,我们继续指定它,以避免破坏尚未升级为支持通用分配器的旧代码(按照 C++11)。


Art*_*yer 5

这并不是已std::allocator<void>被弃用,只是它不是一个明确的专业化。

它曾经的样子是这样的:

template<class T>
struct allocator {
    typedef T value_type;
    typedef T* pointer;
    typedef const T* const_pointer;
    // These would be an error if T is void, as you can't have a void reference
    typedef T& reference;
    typedef const T& const_reference;

    template<class U>
    struct rebind {
        typedef allocator<U> other;
    }

    // Along with other stuff, like size_type, difference_type, allocate, deallocate, etc.
}

template<>
struct allocator<void> {
    typedef void value_type;
    typedef void* pointer;
    typedef const void* const_pointer;

    template<class U>
    struct rebind {
        typdef allocator<U> other;
    }
    // That's it. Nothing else.
    // No error for having a void&, since there is no void&.
}
Run Code Online (Sandbox Code Playgroud)

现在,由于std::allocator<T>::referencestd::allocator<T>::const_reference已被弃用,因此不需要对void. 您可以只使用std::allocator<void>, 以及std::allocator_traits<std::allocator<void>>::template rebind<U>get std::allocator<U>,但无法实例化std::allocator<void>::allocates

例如:

template<class Alloc = std::allocator<void>>
class my_class;  // allowed

int main() {
    using void_allocator = std::allocator<void>;
    using void_allocator_traits = std::allocator_traits<void_allocator>;
    using char_allocator = void_allocator_traits::template rebind_alloc<char>;
    static_assert(std::is_same<char_allocator, std::allocator<char>>::value, "Always works");

    // This is allowed
    void_allocator alloc;

    // These are not. Taking the address of the function or calling it
    // implicitly instantiates it, which means that sizeof(void) has
    // to be evaluated, which is undefined.
    void* (void_allocator::* allocate_mfun)(std::size_t) = &void_allocator::allocate;
    void_allocator_traits::allocate(alloc, 1);  // calls:
    alloc.allocate(1);
}
Run Code Online (Sandbox Code Playgroud)