某些 STL 容器不匹配 std::allocator

mismatched std::allocator for some of STL containers

使用不匹配的 std::allocator 特化(当然,除了 void 的特化)作为 STL 容器的模板参数在技术上是否有效(不是所有容器,但在下面列举加上 unordered_(多)map/set)?以下代码编译正常。

#include <list>
#include <forward_list>
#include <deque>
#include <set>
#include <map>

int main()
{
    struct A { bool operator < (A) const { return true; } };
    struct B {};
    struct C {};
    std::list< A, std::allocator< C > > l;
    std::forward_list< A, std::allocator< C > > fl;
    std::deque< A, std::allocator< C > > d;
    std::set< A, std::less< A >, std::allocator< C > > s;
    std::multiset< A, std::less< A >, std::allocator< C > > ms;
    std::map< A, B, std::less< A >, std::allocator< C > > m;
    std::multimap< A, B, std::less< A >, std::allocator< C > > mm;
}

我认为这是由于分配器立即反弹到底层节点类型而与其源类型无关。

我会说这是 UB(至少在 C++11 中),因为指定的分配器具有与 [=11= 不同的 value_type ] 容器违反了 分配器感知容器要求 ,这意味着这些实例不符合一般容器要求。此外,我在 C++11 标准中找不到任何内容表明分配器类型将从作为模板参数提供的类型中反弹。


1. [container.requirements.general] 部分告诉我们:

13) All of the containers defined in this Clause and in (21.4) except array meet the additional requirements of an allocator-aware container, as described in Table 99.

2. 分配器感知容器要求 说:

Requires: allocator_type::value_type is the same as X::value_type.

  1. [default.allocator] 部分指定

typedef T value_type;

作为命名空间 stdallocator 模板的成员。

4. [multimap.overview] 部分包含:

template <class Key, class T, class Compare = less<Key>,
    class Allocator = allocator<pair<const Key, T> > >
class multimap {
    [...]
    typedef Allocator allocator_type;
    [...]
 };

(对其他容器有类似的发现。)