In error: use of deleted function an error is explained, but it is not explained how to resolve the error. Consider the following c++ code.
struct foo{
int& i;
};
int main() {
int i = 0, j = 1;
foo v = {i};
v = {j};
return 0;
}
This results in error: use of deleted function ‘foo& foo::operator=(foo&&)’
referring to v = {j};
. This can be resolved as follows.
struct foo{
int& i;
};
int main() {
int i = 0, j = 1;
foo v = {i};
foo v2 = {j};
return 0;
}
But this is ridiculous. I don't want to declare a new variable, I just want to get rid of the old instance of v
and assign it a new value. Is there really no way to simply redefine v
?
Since your struct foo
contains a member i
which is a reference, it is non-copyable and non-assignable.
In order to make it copyable/assignable, you can use std::std::reference_wrapper
:
std::reference_wrapper is a class template that wraps a reference in a copyable, assignable object.
#include <functional> // for std::reference_wrapper
struct foo {
std::reference_wrapper<int> i;
};
int main() {
int i = 0, j = 1;
foo v = { i };
v = { j };
return 0;
}