<分区>
记录在案here , std::bitset::operator^=
返回 *this
。从这一点以及对诸如 +=, |=, *=
等运算符的“通常”解释,我们可以合理地假设给定的 std::bitset
实例(相同size) a
和 b
,表达式 (a^=b).count()
将存储按位 XOR 的结果
操作,a
中的 count()
将返回 a
中设置为 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::bitset
的实现(参见 here )似乎表明返回的引用确实是对 lhs 对象的引用(a
在我的例子中)。那么……为什么会这样?