'C++ closure capture variable
In the Cow() function. I'm trying to capture the variable weight to the closure. But it doesn't work correctly. Variable weight is not captured to the closure. When I was trying to run getWeight() function. It returned an uninitialized value. Also setWeight() does not work.
#include <iostream>
struct Mammal {
std::function<void()> speak;
std::function<int()> getWeight;
std::function<void(int)> setWeight;
};
Mammal *Cow() {
int weight = 100;
auto *m = new Mammal();
m->speak = []() { puts("momo~~ momo~~"); };
m->getWeight = [&]() { return weight; };;
m->setWeight = [&](int w) { weight = w; };
return m;
}
int main() {
Mammal *c = Cow();
std::cout << "Cow Weight: " << c->getWeight() << '\n';
c->setWeight(200);
std::cout << "Cow New Weight: " << c->getWeight() << '\n';
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
