如cppreference.com所说,
地图通常以红黑树的形式实现。
因此,移动std::map
只是将指针移动到根node
+其他信息(例如大小)。为什么std::map
的move构造函数未标记为noexcept
?
答案 0 :(得分:13)
这是因为我无法让所有实现者都陷入可以节省map
的无资源状态。例如,即使在默认构造状态下,实现也需要有一个指向的终端节点。允许(但不是必需)将终端节点放在堆上的实现。
A moved-from map must be in a valid state.即从map
移出的移动必须有一个指向end()
被调用时的结束节点。在进行移动构造之前,map
中将有一个要从其移动的末端节点。在移动构造之后,必须存在两个末端节点:一个在新的map
中,一个在移动的`map中。
如果末端节点在堆上,则意味着move构造函数不转移末端节点的所有权,因此必须为新的map分配新的末端节点。或确实转移了末端节点,但随后必须分配一个新节点以留在移出的源中。
如果将结束节点嵌入在map
数据结构本身中,则永远不需要在堆上分配它。构造map
时,它会自动“分配在堆栈上”。
如果需要,可以允许执行map
移动构造函数noexcept
,只是不需要这样做。
这里是我几年前采用的实现中的survey of the noexcept-state of the default constructor, move constructor and move assignment operator of the containers。此调查假设每个容器为std::allocator
。我只是对map
进行了检查,结果没有改变。
如果您想自己进行此调查,请使用以下代码:
#include "type_name.h"
#include <iostream>
#include <type_traits>
#include <deque>
#include <forward_list>
#include <list>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
template <class C>
void
report()
{
using namespace std;
const auto name = type_name<C>();
if (is_nothrow_default_constructible<C>::value)
std::cout << name << " is noexcept default constructible\n";
else
std::cout << name << " is NOT noexcept default constructible\n";
if (is_nothrow_move_constructible<C>::value)
std::cout << name << " is noexcept move constructible\n";
else
std::cout << name << " is NOT noexcept move constructible\n";
if (is_nothrow_move_assignable<C>::value)
std::cout << name << " is noexcept move assignable\n\n";
else
std::cout << name << " is NOT noexcept move assignable\n\n";
}
int
main()
{
using namespace std;
report<deque<int>>();
report<forward_list<int>>();
report<list<int>>();
report<vector<int>>();
report<string>();
report<map<int, int>>();
report<set<int>>();
report<unordered_map<int, int>>();
report<unordered_set<int>>();
}
"type_name.h"
来自this answer。