gpt4 book ai didi

c++ - 不支持 vector 的 noexcept 要求

转载 作者:行者123 更新时间:2023-11-30 05:04:09 24 4
gpt4 key购买 nike

从技术上讲,noexcept specified move c'tor 是 vector 使用 move 而不是复制 c'tor 的要求。

我发现 GCC 7 不是这种情况。

std::vector<A> v;
v.push_back(A("555")); //triggers move c'tor

只要 A 实现了 move c'tor 并且不需要将 move c'tor 指定为 noexcept ,上面的方法就可以工作。

我想知道这是 GCC 问题还是跨编译器正常?
还是我误解了什么?

最佳答案

标准不需要 noexceptT move 构造函数以便在调用 std::vector<T>::push_back(T&&) 时使用它

这是标准关于 push_back(T&& rv) 的内容(参见 [sequence.reqmts]):

Appends a copy of rv.
Requires: T shall be MoveInsertable into [the vector].

MoveInsertible是一个奇特的概念,仅意味着可以使用右值引用*构造您的类型。例如。通过 move 构造函数,但通过复制构造也不异常(exception)。

我认为您将此与以下事实混淆了,这取决于是否声明了 move 构造函数 noexcept与否,std::vector可以做出不同的异常保证。右值引用见“备注”push_back ([vector.modifiers]):

Remarks: ... If an exception is thrown other than by the copy constructor, move constructor, assignment operator, or move assignment operator of T or by any InputIterator operation there are no effects. If an exception is thrown while inserting a single element at the end and T is CopyInsertable or is_nothrow_move_constructible<T>::value is true, there are no effects. Otherwise, if an exception is thrown by the move constructor of a non-CopyInsertable T, the effects are unspecified.


*更具体一点,你的类型是否是MoveInsertible进入vector或不是分配器依赖。也就是说,对于分配器 A你的vector , 以下内容必须格式正确:

allocator_traits<A>::construct(m, p, rv)
  • m是你的分配器的一个实例 A
  • p是指向您的类型 ( T* ) 的指针(更准确地说它是可以容纳 T 的对齐存储)
  • rv是我们试图插入的右值 ( T&& )

关于c++ - 不支持 vector 的 noexcept 要求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49073358/

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