如果我没有遗漏什么,根据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);
}