具有 const 成员的结构向量?
假设我有
#include <string>
#include <vector>
using namespace std;
struct Student
{
const string name;
int grade;
Student(const string &name) : name(name) { }
};
那么,我该如何保留学生的向量?
How do I, then, keep a vector of students?
int main()
{
vector<Student> v;
// error C2582: 'operator =' function is unavailable in 'Student'
v.push_back(Student("john"));
}
有没有办法做到这一点,或者我必须在堆上分配所有学生,并改为存储指向每个学生的指针?
Is there even a way to do this, or must I allocate all the students on the heap, and store a pointer to each of them instead?
推荐答案
你不能.您的类型违反了可分配";对标准容器的要求.
You can't. Your type violates the "Assignable" requirement for standard containers.
ISO/IEC 14882:2003 23.1 [lib.container.requirements]/3:
ISO/IEC 14882:2003 23.1 [lib.container.requirements] / 3:
这些组件中存储的对象类型必须满足CopyConstructible
的要求types (20.1.3),以及 Assignable
类型的附加要求.
The type of objects stored in these components must meet the requirements of
CopyConstructible
types (20.1.3), and the additional requirements ofAssignable
types.
来自表 64(Assignable
要求):
From table 64 (Assignable
requirements):
在表64中,T
是用于实例化容器的类型,t
是T
的值,u
是(可能是 const
)T
的值.
In Table 64,
T
is the type used to instantiate the container,t
is a value ofT
, andu
is a value of (possiblyconst
)T
.
表达式:t = u
;返回类型:T
;后置条件:t
等价于 u
expression: t = u
; return type: T
; post-condition: t
is equivalent to u
理论上,std::vector
等价物可以选择在所有情况下进行销毁和复制构造,但这不是已选择的合约.如果不需要重新分配,则对 vector::operator=
和 vector::assign
等内容使用包含类型的赋值运算符可能会更有效.
In theory, a std::vector
equivalent could choose to do destruction and copy construction in all cases, but that's not the contract that has been chosen. If reallocation isn't required, then using the contained type's assignment operator for things like vector::operator=
and vector::assign
might be significantly more efficient.
相关文章