Why is this snippet involving a static lambda in a class a memory leak?

Viewed 50

I ran into this snippet of code recently. Valgrind says that there's a memory leak, but I have no idea why:

#include <iostream>
#include <set>
#include <map>
#include <memory>
 
class Player {
public:
    Player() {
        static auto foo = [this]() {
            nums_.insert(0);
        };
        foo();
    }
private:
    std::set<int> nums_;
};
 
int main() {
    std::map<std::string, std::shared_ptr<Player>> players;
    players.insert({"eenz", std::make_shared<Player>()});
    players.erase("eenz");
    players.insert({"eenz", std::make_shared<Player>()});
}

When I remove static from the lambda, the memory leak goes away. I tried to reason out why this was a memory leak, but I had no luck. Would anyone know the reason why this is a memory leak?

0 Answers
Related