c++ - How do I implement an overloaded copy assignment operator for a reference (proxy) class? -
as assignment have create template bit array class , part of overloading index operator. told use proxy class , given sample code go off of:
class bits { ... class reference { bits& b; int pos; public: reference(bits& bs, int p) : b(bs) { pos = p; } reference& operator=(bool bit) { // set bit in position pos true or false, per bit if (bit) b.data |= (1u << pos); else b.data &= ~(1u << pos); return *this; } operator bool () const { // return true or false per bit in position pos return b.data & (1u << pos); } }; reference operator[](int pos) { return reference(*this, pos); }
my code reads follows (altered fit bit array):
template <class itype = size_t> class bitarray { ... class bitproxy { bitarray& b; size_t pos; public: bitproxy(bitarray& ba, size_t p) : b(ba) { pos = p; } bitproxy& operator=(bool bit) { b.assign_bit(pos, bit); return *this; } operator bool() const { return b.read_bit(pos); } }; bitproxy operator[](size_t bitpos) { if (bitpos >= arrsize) throw logic_error("provided index out of range"); else return bitproxy(*this, bitpos); } bool operator[](size_t pos) const { if (pos >= arrsize) throw logic_error("provided index out of range"); else return read_bit(pos); }
my code works , passes of tests (the tbitarray.cpp file) when run in visual studio, doesn't work when run through g++ on mac. instead comes error message:
tbitarray.cpp:141:17: error: object of type 'bitarray<unsigned long>::bitproxy' cannot assigned because copy assignment operator implicitly deleted b9[0] = b10[0] = b10[1]; ^ ./bitarray.h:166:13: note: copy assignment operator of 'bitproxy' implicitly deleted because field 'b' of reference type 'bitarray<unsigned long> &' bitarray& b; ^
the reference sample code compiles , runs without issues on both windows or mac.
i understand why copy assignment being implicitly deleted, don't understand why sample code works (when it's in same basic format) , why code run on windows machine, not unix-based machine.
i'm not sure go here , i've tried everything. there sort of workaround this?