gpt4 book ai didi

c++ - 为什么std::map的move构造函数不是noexcept?

转载 作者:行者123 更新时间:2023-12-01 14:57:01 37 4
gpt4 key购买 nike

正如cppreference.com所说,

Maps are usually implemented as red-black trees.



因此,移动 std::map只是将指针移动到根 node +其他信息(例如大小)。为什么 std::map的move构造函数未标记为 noexcept

最佳答案

这是因为我无法让所有实现者都陷入可以将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

关于c++ - 为什么std::map的move构造函数不是noexcept?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63785080/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com