c++ - 用户定义类型的 vector

标签 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
...

哪里出错了?

最佳答案

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

你最可能想要的是

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

创建 t 的拷贝然后将其存储在 vector 中。

您实际上可以在编译器错误消息中看到问题,尽管它们非常隐晦。编译器无法为 *allocator<Test&> 生成代码,它负责存储在 vector 中的对象的内存分配——没有办法为引用分配内存。

关于c++ - 用户定义类型的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11043364/

相关文章:

c++ - 如果链接到未使用的库,可执行文件的构建是否不同?

c++ - 如何从映射中获取值并在 C++ 的 switch 语句中使用它?

C++ std::ref(T) 和 T& 之间的区别?

vue.js - 视觉 : Access Vue component method inside rendered named slot

c++ - 在赋值运算符内制作浅拷贝

c++ - 练习 : for cycle and array

C++ 显式构造函数和迭代器

c++ - GCC 和 Clang 不同意 lambda 的 constexpr-ness?

使用#pragma GCC optimize 优化 C 代码

c - 在 cygwin 的 vi 编辑器中编写第一个 c 程序