Please conform if I am correct and tell me whether there is a better solution:
I understand that objects with constant members like int const width;
can not be handled by the synthetic assignment operator that is implicitly created by the compiler. But QList (and I suppose std::list, too) needs a working assignment operator. So when I want to use objects with constant members and QList I have three possibilities:
Is that correct? Are there other elegant solutions?
Also I wonder whether I can:
EDIT: I never assign objects of this class myself. They are only created by the copy constructor or by an overloaded constructor. So the assignment operator is only required by the container not by myself.
EDIT2: This is the assignment operator I created. I am not sure if its correct though. Cell has a two parameter constructor. These parameters set the two constant members with initialization lists. But the object also contains other variable (non const) members.
Cell& Cell::operator=(Cell const& other)
{
if (this != &other) {
Cell* newCell = new Cell(other.column(), other.row());
return *newCell;
}
return *this;
}
EDIT3: I found this thread with almost the same question: C++: STL troubles with const class members All answers combined together answered my questions.
I'll try to bundle the answers in short:
The main problem is that QList requires the assignment operator to be present because they internally use assignment. Thus they mix implementation with interface. So although YOU don't need the assignment operator QList won't work without it. source
@ 3. There is std::List but it doesn't offer constant time access to elements, while QList does.
@ 2. It is possible by creating a new object with the copy constructor and the desired properties and returning it*. Although you circumvent the const property it is still better than using no const at all because you would allow the container to cheat here but still prevent users to do this themselves which was the original intention of making this member constant.
But take into account that creating an overloaded assignment operator adds to the complexity of the code and might introduce more errors than the const-ing of the members would solve in the first place.
@ 1. In the end this seems to be the easiest solution. As long as it's private you just have to pay attention that the object doesn't change it itself.
@ 4. No way to force him. He wouldn't know how because the variable is constant and at some point he would have to do this->row = other.row
with int const row;
previously defined. And const means constant even in this case. one source
@ 5 QList has no options of this kind.
Additional solutions:
*Not sure about this at the moment.