A certain type of vector

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 mistake?

+4
source share
3 answers

The problem is that you are trying to create a link vector. The type of object that should be stored in the vector must be assigned, which does not apply to links. The link can only be initialized after the announcement and cannot be changed later.

What you most likely want is

 Test t(31415); std::vector<Test> vet; vet.push_back(t); 

which creates a copy of t , which is then stored in the vector.

You can see the problem in compiler error messages, although they are rather cryptic. The compiler cannot generate code for *allocator<Test&> , which takes care of memory allocation for objects that will be stored in the vector - there is no way to allocate memory for the link.

+8
source

you can use the new C ++ 11 move-semantics or use a vector of pointers to Test if copying does not fit the requirement

+1
source

As others have said, you can instead create a vector of pointers:

 vector<Object*> vet; ... while (blabla) { Object* I = SF.CurObject++; vet.push_back(I); } 

You can use the link if you insist:

 Object& Iref = *I; 
+1
source

All Articles