I have const objects in a deque:
class ConstClass {
public:
ConstClass(int variable): variable_(variable) {}
private:
const int variable_;
};
std::deque<ConstClass> objects;
objects.push_back(ConstClass(1));
objects.push_back(ConstClass(2));
objects.push_back(ConstClass(3));
How can I replace the second element with another one?
If I try to do it using [] = or std::replace, I get:
Compiler could not generate operator = for class 'ConstClass'
The only way I can think of is creating empty deque, push_back() all elements from 'objects' there (replacing the N-th element with the new one), then clear() the 'objects' deque and push_back() the copied elements from the temp deque back to 'objects'..
I am sure there is a more sane way to do it, but I don't know how?
You can't. Your container is invalid because its element type must be copy-assignable or move-assignable, and yours is neither. This isn't diagnosed at construction, but you've already seen the resulting compilation error that occurs when you try to perform operations that rely on this property.
You could make it legal and compilable by overloading the copy and move assignment operators of your element type to ignore the const
member, but it's not clear that this would make any sense.
Either store std::unique_ptr
s to dynamically-allocated objects, or rethink the model.