Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector of user defined type

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?

like image 480
JohnTortugo Avatar asked Dec 21 '22 20:12

JohnTortugo


1 Answers

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.

like image 141
bbtrb Avatar answered Dec 24 '22 03:12

bbtrb