I had a problem that I donβt understand, and I was hoping that someone here could give some insight. The simplified code is as follows (the source code is an implementation of a user queue / iterator queue):
class B { public: B() {}; class C { public: int get(); C(B&b) : b(b){}; private: B& b; }; public: C get_c() { return C(*this); } }; int main() { B b; B::C c = b.get_c(); c = b.get_c(); return EXIT_SUCCESS; }
This compiles the following error when compiling:
foo.cpp: In member function 'B::C& B::C::operator=(const B::C&)': foo.cpp:46: error: non-static reference member 'B& B::C::b', can't use default assignment operator foo.cpp: In function 'int main()': foo.cpp:63: note: synthesized method 'B::C& B::C::operator=(const B::C&)' first required here
I can get around this using two separate C variables, since they must be independent C objects, but this only hides the problem (I still don't understand why I cannot do this).
I think the reason is that the link cannot be copied, but I do not understand why. Do I need to provide my own assignment operator and copy constructor?
c ++ assignment-operator reference
laura
source share