c++ - 具有 const 成员的结构 vector ?

标签 c++ constants c++03

假设我有

#include <string>
#include <vector>
using namespace std;

struct Student
{
    const string name;
    int grade;
    Student(const string &name) : name(name) { }
};

那么,我该如何保持学生的 vector ?

int main()
{
    vector<Student> v;

    // error C2582: 'operator =' function is unavailable in 'Student'
    v.push_back(Student("john"));
}

有没有办法做到这一点,还是我必须在堆上分配所有学生,然后存储一个指向每个学生的指针?

最佳答案

你不能。您的类型违反了标准容器的“可分配”要求。

ISO/IEC 14882:2003 23.1 [lib.container.requirements]/3:

The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types.

来自表 64(可分配 要求):

In Table 64, T is the type used to instantiate the container, t is a value of T, and u is a value of (possibly const) T.

expression: t = u; return type: T; post-condition: t is equivalent to u

理论上,std::vector 等价物可以选择在所有情况下进行销毁和复制构造,但这不是已选择的契约。如果不需要重新分配,则对 vector::operator=vector::assign 之类的内容使用包含类型的赋值运算符可能会更有效。

关于c++ - 具有 const 成员的结构 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8467968/

相关文章:

c++ - 从文件中加载 const 命名空间变量值

c++ - C++03 保证 `double` 准确表示小整数吗?

c++ - 将 std::ptr_fun 用于成员函数

python - Boost不将模块暴露给python

c++ - QVector<float> 或 float* - Qt 内存管理优于 native C++?

c++ - 什么是 "symbolic constants"和 "magic constants"?

c++ - 通过迭代器更改类成员

c++ - 运算符重载以构造异常消息

c++ - C 或 C++ websocket 客户端工作示例

c++ - `0x2` 是 C++ 中的空指针吗?