Re: vector.resize assignment operator problem
"Bram Kuijper" <a.l.w.kuijper@rug.nl> wrote in message
news:f4ougm$7q4$1@info.service.rug.nl...
Hi all,
I am trying to resize a vector of objects (MyObj below), which contain
references to other objects (OtherObj, see below). However, apparently
somewhere in the resize operation an assignment is done of the referenced
OtherObj object (according to the compiler messages). This is strange,
since the referenced OtherObj is initialized using member initialization
lists. Anyone a clue?
thanks,
Bram Kuijper
this is the source. Compiler messages (g++ 4.1.3) are listed below.
#include<vector>
using namespace std;
class OtherObj
{
public:
OtherObj()
{}
};
class MyObj
{
private:
OtherObj const &objref;
public:
MyObj(OtherObj const &obj)
:
objref(obj)
{}
MyObj(MyObj const &other)
:
objref(other.objref)
{}
};
int main()
{
OtherObj obj = OtherObj(); //fine
vector<MyObj> first(3, MyObj(obj)); //okay
first.resize(10, MyObj(obj)); //ERROR
return 0;
}
[snip bunch of error deetail]
test.cpp:14: error: non-static reference member ?const OtherObj&
MyObj::objref?, can't use default assignment operator
OtherObj& is a reference. A reference in your class can't be assigned by
the default assignment operator. References in a class need to be
initialized, not assigned, that's where the problem is coming in.
*** Especially this error message above is puzzling me ***
/usr/include/c++/4.1.3/bits/stl_algobase.h: In static member function
?static void std::__fill<<anonymous> >::fill(_ForwardIterator,
_ForwardIterator, const _Tp&) [with _ForwardIterator =
__gnu_cxx::__normal_iterator<MyObj*, std::vector<MyObj,
std::allocator<MyObj> > >, _Tp = MyObj, bool <anonymous> = false]?:
/usr/include/c++/4.1.3/bits/stl_algobase.h:529: note: synthesized method
?MyObj& MyObj::operator=(const MyObj&)? first required here