用户定义类型的向量

时间:2012-06-15 00:59:48

标签: c++ gcc reference allocation

尝试编译此代码时:

#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报告各种错误,从:

开始
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
...

错误在哪里?

3 个答案:

答案 0 :(得分:8)

问题在于您正在尝试创建引用向量。要存储在向量中的对象类型必须是可分配的,而引用则不是这种情况。引用只能在声明时初始化,以后不能更改。

你最想要的是

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

创建t的副本,然后存储在向量中。

您实际上可以在编译器错误消息中看到问题,尽管它们非常神秘。编译器无法为*allocator<Test&>生成代码,该代码负责处理要存储在向量中的对象的内存分配 - 无法为引用分配内存。

答案 1 :(得分:1)

如果复制不符合要求,您可以使用新的c ++ 11 move-semantics或使用指向Test的指针

答案 2 :(得分:1)

正如其他人所说,你可以创建一个指针向量:

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

如果你坚持,你仍然可以使用参考:

Object& Iref = *I;