问题描述
使用不匹配的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:
2. 可识别分配器的容器要求说:
2. The Allocator-aware container requirements says:
-
[default.allocator]
部分指定
- Section
[default.allocator]
specifies
作为名称空间std
中allocator
模板的成员.
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不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!