Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There's no value type in C++ to represent a single bit, so when you use the <code>[]</code> operator to access an element of a bitset, what you get is a <em>proxy object</em> that serves as an alias for the bit you requested. Assigning to that proxy object changes the corresponding bit value in the original bitset object.</p> <p>As <a href="https://stackoverflow.com/questions/2003255/why-the-stdswap-of-bits-in-a-stdbitset-instance-doesnt-work/2003286#2003286">Victor's answer</a> shows, your code doesn't compile with GCC. But let's suppose the call to <code>swap</code> would compile. You'd get code that amounts to something like this:</p> <pre><code>void swap(std::bitset&lt;2&gt;::reference&amp; a, std::bitset&lt;2&gt;::reference&amp; b) { std::bitset&lt;2&gt;::reference tmp = a; a = b; b = tmp; } </code></pre> <p>The <code>tmp</code> declaration initializes the variable with <code>a</code>, but that doesn't make a copy of the bit. Instead, it makes a copy of the proxy object, so <code>tmp</code> <em>refers</em> to the same bit in the same bitset that <code>a</code> refers to. The next line assigns <code>b</code> to <code>a</code>, which copies the bit value from the location <code>a</code> refers to and stores it in the bit location <code>b</code> refers to. Finally, there's the assignment of <code>tmp</code> into <code>b</code>. But remember that <code>tmp</code> still refers to the bit that <code>a</code> refers to. Reading <code>tmp</code> is the same as reading <code>a</code>, so you ultimately get the same effect you'd get if <code>swap</code> were just these two lines:</p> <pre><code>a = b; b = a; </code></pre> <p>In your code, <code>a</code> is 0 and <code>b</code> is 1, so with those two assignment statements, 11 is exactly what we'd expect to see.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload