如文件所述
here
,
std::bitset::operator^=
收益率
*this
. 从这个和从“通常”的解释,如
+=, |=, *=
人们可以合理地假设
std::bitset
实例(大小相同)
a
和
b
,表达式
(a^=b).count()
将按位存储结果
XOR
操作在
一
那
count()
将返回
一
设置为
true
. 但是,正如下面的最小示例所示,会发生意外情况:
#include <iostream>
#include <bitset>
int main()
{
constexpr unsigned int N=6;
std::bitset<N> a;
std::bitset<N> b;
a.flip();//111111
b[0]=1;
b[4]=1;//b is now 010001 (assuming least significan bit on the right end of the string)
std::cout<<"a=="<<a.to_string()<<std::endl;
std::cout<<"b=="<<b.to_string()<<std::endl;
std::cout<<"(a xor b) to string=="<<(a^=b).to_string()<<std::endl;
//Here is the unexpected part!
std::cout<<"(a xor b) count=="<<(a^=b).count()<<std::endl;
//Note that the following lines would produce the correct result
//a^=b;
//std::cout<<a.count()<<std::endl;
return 0;
}
输出是
a==111111
b==010001
(a xor b) to string==101110
(a xor b) count==6 //this is wrong!!!!! It should be 4...
快速查看
STD::比特集
(见
here
)似乎表明返回的引用确实是对lhs对象的引用(
一
在我的例子中)。所以…为什么会这样?