gpt4 book ai didi

c++ - 为什么 std::exchange 不是 noexcept?

转载 作者:太空狗 更新时间:2023-10-29 20:35:21 31 4
gpt4 key购买 nike

根据标准(N4659,§23.2.4,[utility.exchange]),std::exchange应该做 std::move和一个 std::forward :

template <class T, class U = T> T exchange(T& obj, U&& new_val);

Effects: Equivalent to:

T old_val = std::move(obj);
obj = std::forward<U>(new_val);
return old_val;

两者都是 moveforward标记为 noexcept :
(N4659,§23.2.5,[转发]):

template <class T> constexpr T&& forward(remove_reference_t<T>& t) noexcept;template <class T> constexpr T&& forward(remove_reference_t<T>&& t) noexcept;

Returns: static_cast<T&&>(t).

(...)

template <class T> constexpr remove_reference_t<T>&& move(T&& t) noexcept;

Returns: static_cast<remove_reference_t<T>&&>(t).

那为什么不是 exchange noexcept ?是否还有其他原因,或者委员会只是忽略了这一点?这是在提议还是我可以写一个?

最佳答案

不同于 std::swap,它在默认情况下仅依赖于移动构造函数,因此通常应该是 noexceptstd::exchange 可能如果需要复制新值,则分配资源。当 new_valU&& 并且移动赋值和旧值的移动抛出时,条件 noexcept 可能有一个复杂的表达式,好像还没有人提出这样的建议

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

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