[英]C++, set bool to false, return old
This code:这段代码:
bool b = isTrue;
isTrue = false;
saves old isTrue
value to b
, then sets isTrue
to false
.将旧
isTrue
值保存到b
,然后将isTrue
设置为false
。 All good, but is there a way to perform this in one line?一切都很好,但是有没有办法在一行中执行此操作? In the end I would like to achieve this:
最后我想实现这一点:
bool b = isTrue ? /* assign true and flip `isTrue` value to false */ : false;
std::exchange
can be used to do exactly this: std::exchange
可用于执行此操作:
bool b = std::exchange(isTrue, !isTrue);
It's equivalent to:它相当于:
bool b = (isTrue := !isTrue)
Where :=
is a magical assignment operator that returns the old value rather than the freshly-assigned value.其中
:=
是一个神奇的赋值运算符,它返回旧值而不是新分配的值。
If you instead would like b
to have the old value of isTrue
and set isTrue
to false
, as the discussion in the comments suggests, you can do this with:如果您希望
b
具有isTrue
的旧值isTrue
设置为false
,正如评论中的讨论所建议的那样,您可以这样做:
bool b = std::exchange(isTrue, false);
it'll be这将是
#include <iostream>
int main()
{
bool t = !false;
bool b = false;
// b = t, t = !t;
t = !(b = t);
std::cout << std::boolalpha << "b : " << b << " , " << "t : " << t << " . " << "give me a bottle of rum!" << std::endl;
return 0;
}
line that's comented works too评论的行也有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.