如果我没有遗漏什么,根据Allocator的要求,std::vector
的Allocator
模板参数不需要是默认可构造的。
然而,以下最小的示例无法编译(实时演示(:
#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);
}
std::vector<int, stateful_allocator<int>> x(0)
正在调用std::vector
构造函数重载,该重载占用一个大小,而不是隐式地将0
转换为stateful_allocator
(通过将构造函数标记为explicit
,您已经禁用了该重载(。
由于您没有传入分配器实例,因此由于构造函数中的默认参数,一个分配器实例是默认构造的。
尝试:
std::vector<int, stateful_allocator<int>> x(stateful_allocator<int>{0});