pipespups
pipespups

Reputation: 37

Does vector erase method needs class to have = operator?

I'm doing a computer science project where I use stl library vector as vector (Table is a class implemented by me). When I tried to use erase method without having implemented operator= in my class Table it fails. Then I added = and now it works but I'm not sure that was the problem. Is necessary to have operator= in a class to use erase method? This is a sample code:

vector<Table> tables;
Table t("1");
Table t2("2");

tables.push_back(t);
tables.push_back(t2);

tables.erase(tables.begin());//If no operator = is defined this gives problems

Upvotes: 0

Views: 109

Answers (2)

Marshall Clow
Marshall Clow

Reputation: 16670

Consider what happens in your code. You have two Tables in the vector, and then you erase the first one. When you're done, you have one Table and it's in the memory location that the first one "used to be"

To do that, the vector needs to copy/move the second one into the spot where the first one is. It does this via assignment.

Upvotes: 1

eerorika
eerorika

Reputation: 238321

Is necessary to have operator= in a class to use erase method?

Yes, it is required by the standard.

And why it runs without having it defined?

A class has an implicit assignment operator generated by the compiler by default, except in certain cases (for example, if it has sub objects that are not assignable).

Upvotes: 2

Related Questions