这是 std::bitset::operator^= 和 std::bitset::count 的正常行为吗?如果是这样,为什么?

Is this normal behavior for std::bitset::operator^= and std::bitset::count ? If so, why?

如文档所述 herestd::bitset::operator^= returns *this。从这一点和 "usual" 对诸如 +=, |=, *= 等运算符的解释,我们可以合理地假设给定 std::bitset 个实例(相同大小)ab,表达式 (a^=b).count() 将按位 XOR 运算的结果存储在 a 中,而 count() 将 return 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)似乎表明 returned 的引用确实是对 lhs 对象的引用(a 在我的例子中)。那么...为什么会这样?

这与bitset无关。考虑这段代码:

int a = 2;
int b = 3;
std::cout << std::to_string(a *= b) << std::endl; // Prints 6.
std::cout << std::to_string(a *= b) << std::endl; // Prints 18.

您正在使用赋值运算符,因此您的 variable/bitset 每次 都会更改 。在您的情况下,第二次评估产生 ((a ^ b) ^ b),这当然是原始的 a(确实设置了 6 位)。