0
votes

I have a vector like this:

vector<pair<const MyObj&, MyStrut>> alls;

When I do

swap(alls[0], alls[1]);

It complained

binary '=': no operator found which takes a left-hand operand of type '_Ty' (or there is no acceptable conversion

Why?

1
Generally speaking a const MyObj & cannot be assigned to, since it is const. Assignment of a pair<X, Y> generally works by doing an assignment of X and an assignment of Y and, if either of them cannot be assigned, neither can the pair. The default implementation of swap does assignment. - Peter

1 Answers

1
votes

In the process of trying to swap your pairs, it's intrinsically trying to assign from a const reference to a const reference. You can't rebind a reference, so the only thing it could conceivably do is swap the objects referred to by each reference. But since these are const references, even that's impossible.

If you think you need to store a reference in a data structure and manipulate the structure containing it in any way, it's usually the case that you actually want to store a pointer of some sort (e.g. std::shared_ptr) that would allow you to store it in the data structure and reassign (e.g. swap) it within the data structure, while still having an owned pointer to it somewhere else (to preserve the "referenciness" you're relying on).