0

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. Commented Nov 5, 2019 at 2:41

1 Answer 1

1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.