vector of user defined type
Solution 1
The problem is that you are trying to create a vector of references. The object's type to be stored in the vector must be assignable, which is not the case for references. A reference can only be initialized upon declaration and can not be changed later.
What you most probably want is
Test t(31415);
std::vector<Test> vet;
vet.push_back(t);
which creates a copy of t
that is then stored in the vector.
You can actually see the problem in the compiler error messages, although they are quite cryptic. The compiler fails to generate code for a *allocator<Test&>
, which takes care of memory allocation of the objects to be stored in the vector - there is no way to allocate memory for a reference.
Solution 2
you could use the new c++11 move-semantics or use a vector of pointers to Test
if copying doesn't fit the requirements
Solution 3
As others have said, you can create a vector of pointers instead:
vector<Object*> vet;
...
while (blabla) {
Object* I = SF.CurObject++;
vet.push_back(I);
}
You can still use a reference, if you insist:
Object& Iref = *I;
Comments
-
JohnTortugo almost 2 years
When trying to compile this code:
#include <iostream> #include <vector> using namespace std; class Test { int a; public: Test(int pa) : a(pa) { } void print() { std::cout << a << std::endl; } }; int main() { Test t(31415); t.print(); vector<Test &> vet; vet.push_back(&t); return 0; }
gcc 4.4.5-8 report various erros, starting with:
In file included from /usr/include/c++/4.4/i486-linux-gnu/bits/c++allocator.h:34, from /usr/include/c++/4.4/bits/allocator.h:48, from /usr/include/c++/4.4/string:43, from /usr/include/c++/4.4/bits/locale_classes.h:42, from /usr/include/c++/4.4/bits/ios_base.h:43, from /usr/include/c++/4.4/ios:43, from /usr/include/c++/4.4/ostream:40, from /usr/include/c++/4.4/iostream:40, from references.cpp:1: /usr/include/c++/4.4/ext/new_allocator.h: In instantiation of ‘__gnu_cxx::new_allocator<Test&>’: /usr/include/c++/4.4/bits/allocator.h:87: instantiated from ‘std::allocator<Test&>’ /usr/include/c++/4.4/bits/stl_vector.h:71: instantiated from ‘std::_Vector_base<Test&, std::allocator<Test&> >’ /usr/include/c++/4.4/bits/stl_vector.h:171: instantiated from ‘std::vector<Test&, std::allocator<Test&> >’ references.cpp:22: instantiated from here ...
where is the error?