std::exchange
是C++14引入的函数,其规定如下:
这里是cppreference上的一个可能实现:
template< class T, class U = T > T exchange( T& obj, U&& new_value );
Replaces the value of
obj
withnew_value
and returns the old value ofobj
.
template<class T, class U = T>
T exchange(T& obj, U&& new_value)
{
T old_value = std::move(obj);
obj = std::forward<U>(new_value);
return old_value;
}
据我所知,没有什么阻止
std::exchange
被标记为constexpr
。是否有我不知道的原因导致它无法成为constexpr
,还是这只是一个疏忽?
std::exchange
成为constexpr
会带来什么好处? - Sergey Kalinichenkoconstexpr
,对于obj
来说仍然是隐含的const
。因此,如果试图在需要常量表达式的上下文中调用该函数,则该函数是不合法的。将其定义为constexpr
只是纯粹的愚蠢行为,是一个明显的误导。 - StoryTeller - Unslander Monicaobj
是constexpr
。如果是这样的话,std::move(obj)
还有意义吗?如果obj
是constexpr
,那么它不可移动,对吗? - Nawaz