Max Tyler Max Tyler - 3 months ago 22
C++ Question

Removing std::function lambda-wrapped method from std::map

I'm creating a callback system using

std::function
and
std::map
s. The map uses
int
s as keys and the values are
std::function
. I bind methods into those functions. I'm wondering if I call
map.erase(i)
, will that delete the std::function from memory, or will I have a memory leak?

Here is some example code:

#include <iostream>
#include <functional>
#include <map>

using namespace std;

class TestClass{
public:
TestClass(int _i, map<int, function<void()>>& test_map):i(_i){
test_map[i]=[&](){this->lambda_test();};
};
void lambda_test(){cout << "output" << " " << i<< endl;};
private:
int i;
};

int main() {
map<int, function<void()>> test_map;
TestClass* test = new TestClass(1, test_map);
test_map[1]();
delete test;
test_map.erase(1); // <-- here
};


Does the last
test_map.erase(1);
remove the
std::function
from memory?

Answer

While this is not good code, there is no memory leak; you're storing the std::functions in the std::map by value (rather than by pointer), hence std::map::erase will call the destructor of std::function.

Put another way, you're not newing any std::function, so you don't need to delete any std::function.