一些STL容器的std :: allocator不匹配 [英] mismatched std::allocator for some of STL containers

查看:394
本文介绍了一些STL容器的std :: allocator不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用不匹配的std::allocator专门化技术(当然,除了它对void的专门化技术)作为STL容器的模板参数在技术上是否有效(并非全部,但在下面枚举以及unordered_(multi)map/set) ?以下代码可以正常编译.

Is it technically valid to use mismatched std::allocator specialization (surely, except its specialization for void) as a template parameter for STL containers (not all of them, but enumerated below plus unordered_(multi)map/set)? Following code compiles fine.

#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;
}

我相信这是由于分配器立即反弹到基础节点类型,而与它的源类型没有任何关系.

I believe this is due to allocator being immediately rebound to underlying node type without any relation to its source type.

推荐答案

我会说这是 UB (至少在C ++ 11中),因为指定了具有不同value_type中的>违反了可识别分配器的容器要求,这意味着这些实例不符合常规容器要求.此外,我在C ++ 11标准中找不到任何能说明分配器类型要从作为模板参数提供的类型反弹的东西.

I'd say this is UB (at least in C++11) because specifying an allocator which has a different value_type from the value_type of the container violates the allocator-aware container requirements which means those instances do not conform to the general container requirements. Furthermore, I can't find anything in the C++11 standard that says that the allocator types are to be rebound from the type provided as template parameter.

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

 1. Section [container.requirements.general] tells us:

13)本条款和(21.4)中定义的所有容器(数组除外)均满足表99中所述的可识别分配器的容器的其他要求.

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. 可识别分配器的容器要求说:

 2. The Allocator-aware container requirements says:

要求:allocator_type::value_typeX::value_type相同.

  1. [default.allocator]部分指定
  1. Section [default.allocator] specifies

typedef T value_type;

作为名称空间stdallocator模板的成员.

as a member of the allocator template in namespace std.

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

 4. Section [multimap.overview] contains:

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

(对于其他容器也有类似的发现.)

(With similar findings for the other containers.)

这篇关于一些STL容器的std :: allocator不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆