I have a class in which I deleted the copy assignment operator and copy constructor, leaving only a move assignment operator and move constructor. For example:
struct Number {
public:
int *pNum;
Number &operator=(const Number &rhs) = delete;
Number(const Number &rhs) = delete;
Number &operator=(Number &&rhs) {
if (&rhs == this) {
return *this;
}
pNum = rhs.pNum;
rhs.pNum = nullptr;
return *this;
}
Number() = default;
Number(Number &&rhs) {
*this = std::move(rhs);
}
~Number() {
delete pNum;
}
};
Now, I want to use std::move
to capture this class into a lambda. For example:
int main() {
std::function<int(int)> add;
int a = 3;
{
Number n{};
n.pNum = new int;
*n.pNum = 5;
add = [&, capA{std::move(n)}](int) mutable -> int {
int b = *capA.pNum; // 5
return a + b; // 8
};
}
std::cout << add(3);
}
However, it seems that n
would be const
so that c++ would try to use the deleted copy constructor. How would I fix this? (REPL: https://repl.it/@25GrantY/WeirdLambda)