Search code examples
c++c++11std-bitset

C++ bitset reference


Two questions on bitset reference:

Q1. Is there any way we can return a class private member bitset? In the code snippet below (followed by output), I experimented with the regular reference but it won't even modify the bitset member in Foo class.

Q2. From the answers in this question, I understand that regular references do not have enough granularity to point to the single bit stored in bitset since bitset stores them in a more compact form. However, if this is true, how could my code still manage to modify the first bit in b3 in the line b3[1] = 0?

#include <iostream>
#include <bitset>

using namespace std;

class Foo 
{ 
private:
    bitset<4> b1;  
public:
    inline void print_value() 
    {
        cout << "The bitset b1 is: ( "<< b1 << " )" << endl;
    }
    inline void set_all() { b1.set(); }
    inline bitset<4> get_b1() { return b1; }
    inline bitset<4>& get_b1_ref() { return b1; }
}; 

int main()
{
    Foo f;
    f.print_value();
    f.set_all();
    f.print_value();
    auto b2 = f.get_b1();
    b2.flip();
    cout << "The bitset b2 is: ( "<< b2 << " )" << endl;
    f.print_value();
    auto b3 = f.get_b1_ref();
    cout << "The bitset b3 is: ( "<< b3 << " )" << endl;
    cout << "b3[0] is ( " << b3[0] << " )"<< endl;
    cout << "b3[0] is ( " << b3[1] << " )"<< endl;
    b3[1] = 0;
    cout << "The bitset b3 after change is: ( "<< b3 << " )" << endl;
    f.print_value();
}

Output:
The bitset b1 is: ( 0000 )
The bitset b1 is: ( 1111 )
The bitset b2 is: ( 0000 )
The bitset b1 is: ( 1111 )
The bitset b3 is: ( 1111 )
b3[0] is ( 1 )
b3[0] is ( 1 )
The bitset b3 after change is: ( 1101 )
The bitset b1 is: ( 1111 )

Solution

  • With

    auto b3 = f.get_b1_ref();
    

    the deduced type will not be a reference, only the base type bitset<4>. This means b3 is not a reference, and all modifications of b3 or its contents will be limited to the b3 object itself.

    To get a reference you need to explicitly use & in the declaration:

    auto& b3 = f.get_b1_ref();