Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: use of deleted function - solution?

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?

like image 937
SmileyCraft Avatar asked Nov 17 '25 06:11

SmileyCraft


1 Answers

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::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

like image 142
wohlstad Avatar answered Nov 18 '25 19:11

wohlstad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!