I have a class that can't be re-assigned. The actual motive is that it has an std::variant member variable, and the possible types are not re-assignable, due to having some reference member variables (which can't be rebound). This is a very simple version of what we have:
class MyClass
{
public:
MyClass() {}
MyClass(int a) {}
MyClass(MyClass &other) = default;
MyClass(MyClass &&other) = default;
MyClass &operator=(MyClass &) = delete;
MyClass &operator=(MyClass &&) = delete;
};
Now, at some point, I have an array of these objects.
std::array<MyClass, 5> my_array; // default initializes all objects
Eventually, I want to make a new object and put it into the array.
my_array[1] = {69};
But std::array tried to assign, and so I get an error.
error: use of deleted function ‘MyClass& MyClass::operator=(MyClass&&)’
29 | my_array[1] = {69};
| ^
Is there a way to force reconstructing instead of reassigning the element?
No there's no way to force a reconstruction that wouldn't be undefined behaviour, at least not without destroying the preexisting element and using placement new.
Since you mention
std::variantthough: You can change the element type, even after the element is constructed regardless of whether the element type of thestd::variantis copyable/moveable. Just usestd::variant::emplace.The following example implements assignment operators in
MyClassthat make code similar tomy_array[1] = {69};work.