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
?
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
?
2 Answers
Reset to default 4Since 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::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;
}
Live demo
The simplest and most adequate solution here is to use a member pointer instead of a reference. The two are very similar — the main difference is that pointers can change what they refer to, which is exactly what you are trying to do with the assignment. References, by contrast, are immutable aliases for objects.
If you want to assign objects of foo
, reference members simply are the wrong type choice.
i
with a reference to a temporary, a disaster. – Peter - Reinstate Monica Commented Mar 2 at 9:58int& i
intostd::reference_wrapper<int> i
. – wohlstad Commented Mar 2 at 10:00j
would stay valid. – Peter - Reinstate Monica Commented Mar 2 at 10:06