2

如果我没有遗漏什么,根据Allocator的要求, a 的Allocator模板参数std::vector不需要是默认可构造的。

但是,以下最小示例无法编译(现场演示)

#include <vector>


template<typename T>
class stateful_allocator
{
public:
    using value_type = T;

    constexpr explicit stateful_allocator(int s) noexcept
        : m_state(s)
    {}

    template <typename U>
    stateful_allocator(stateful_allocator<U> const& other) noexcept {
        m_state = other.m_state;
    }

    T* allocate(std::size_t) { return nullptr; }
    void deallocate(T*, std::size_t) noexcept {}

private:
    int m_state;
};

template <typename T, typename U>
bool operator==(stateful_allocator<T> const&, stateful_allocator<U> const&) noexcept {
    return true;
}

template <typename T, typename U>
bool operator!=(stateful_allocator<T> const& x, stateful_allocator<U> const& y) noexcept {
    return !(x == y);
}


int main()
{
    std::vector<int, stateful_allocator<int>> x(0);
}
4

1 回答 1

3

std::vector<int, stateful_allocator<int>> x(0)正在调用std::vector构造函数重载,它需要一个大小,而不是隐式转换0stateful_allocator(无论如何你已经通过标记你的构造函数来禁止它explicit)。

由于您没有传入分配器实例,因此由于构造函数中的默认参数,因此默认构造了一个。

尝试:

std::vector<int, stateful_allocator<int>> x(stateful_allocator<int>{0});
于 2020-11-18T21:15:25.270 回答