Why std::vector requires operator =

c++, stl

Solution

This might surprise you:

v.push_back(A(20));
v.push_back(A(10));
std::sort(begin(v), end(v));

There are aspects of vector itself that require assignability, though I don't know, offhand, which (and I can't tell by compiling your code, since my compiler doesn't complain when I remove `operator=()`). According to Wikipedia (which references the relevant portion of the '03 standard), elements must be `CopyConstructible` and `Assignable`.

EDIT: Coming back to this a day later, it seems forehead-slappingly obvious when `std::vector` requires `Assignable` — any time it has to move elements around. Add a call to `v.insert()` or `v.erase()`, for example, and the compile will fail.

Problem

I have a question about a class that we can store in vector. What is the requirement that can be stored in a vector? It seems that such class has to have assignment operator. But I am not sure if that's all or not. Let me give you an example. class A has const int member. If I don't write operator =, it doesn't compile. But in this example, this operator does nothing. This program displays 10 and 20 correctly. It looks that operator = is required but not used in reality. ``` #include <iostream> #include <vector> class A { public: A(int a) : a_(a) {} A& operator =(const A& a2) { return *this;} // Without this, compile fails. void print() const { std::cerr << a_ << std::endl; } private: const int a_; }; int main(int argc, char** argv) { std::vector<A> v; v.push_back(A(10)); v.push_back(A(20)); for (const A& a : v) a.print(); } ```

Original source