I want to store a list of objects in an std::vector, but the objects contain a reference and cannot be assigned to. I can, however, copy-construct the object.
The only option I can think of is to use pointers to wrap the objects and reseat the pointers when they need to be assigned, but the syntax for this would significantly reduce readability, especially when using iterators, and I would prefer an alternative.
Doesn’t work:
std::vector<MyObject> myVector;
//fill the vector
//...
myVector[1] = object1;
Smart pointers sacrifice readability:
std::vector<std::unique_ptr<MyObject>> ptrVector;
//fill the vector
//...
ptrVector[1] = std::unique_ptr<MyObject>(new MyObject(object1));
Are there any other methods to use unassignable objects in an std::vector?
This isn’t a direct answer to your question as I can’t offer a replacement for
std::vector, or a different way of using it that allows you to do what you need to.However, if it is possible to modify the definition of
MyObject, it may be an option to change it so it usesstd::reference_wrapperinstead of conventional references. That would allowMyObjectto be assignable.Example:
Caveat: Existing code may already contain direct assignments to the reference member (i.e. the member called
_iin the code above). Those assignments were intended to change the value of the object the reference refers to. When replacing the reference with astd::reference_wrapper, all direct assignments_i = xmust be replaced with_i.get() = x, otherwise the semantics of the program change entirely.(EDIT) If the references used are const-references
const T&, astd::reference_wrapper<const T>can be used. Using the example above, the definition ofMyObjectthen changes to this: