Let’s say I have
#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:
From table 64 (
Assignablerequirements):In theory, a
std::vectorequivalent 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 likevector::operator=andvector::assignmight be significantly more efficient.