std::map 是否分配其比较器?
Does std::map assign its comparator?
是否需要 std::map
复制赋值(样式 map1 = map2;
)以将 map2
的比较器复制到 map1
?
我已经测试过实际的实现可以做到这一点。我对它在 C++ 标准中的指定位置更感兴趣。
如果我们查看 [[=21=]]/12,我们有
When an associative container is constructed by passing a comparison object the container shall not store a pointer or reference to the passed object, even if that object is passed by reference. When an associative container is copied, either through a copy constructor or an assignment operator, the target container shall then use the comparison object from the container being copied, as if that comparison object had been passed to the target container in its constructor.
强调我的
因此,在您的示例中,map1
将获得 map2
的比较器的副本。
从cplusplus.com你可以看到在copy-constructor (3)下说
(3) map (const map& x);
The container keeps an internal copy of alloc and comp, which are used
to allocate storage and to sort the elements throughout its lifetime.
The copy constructor (3) creates a container that keeps and uses
copies of x's allocator and comparison object.
是否需要 std::map
复制赋值(样式 map1 = map2;
)以将 map2
的比较器复制到 map1
?
我已经测试过实际的实现可以做到这一点。我对它在 C++ 标准中的指定位置更感兴趣。
如果我们查看 [[=21=]]/12,我们有
When an associative container is constructed by passing a comparison object the container shall not store a pointer or reference to the passed object, even if that object is passed by reference. When an associative container is copied, either through a copy constructor or an assignment operator, the target container shall then use the comparison object from the container being copied, as if that comparison object had been passed to the target container in its constructor.
强调我的
因此,在您的示例中,map1
将获得 map2
的比较器的副本。
从cplusplus.com你可以看到在copy-constructor (3)下说
(3) map (const map& x);
The container keeps an internal copy of alloc and comp, which are used to allocate storage and to sort the elements throughout its lifetime. The copy constructor (3) creates a container that keeps and uses copies of x's allocator and comparison object.