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

I am creating a callback system using std::functionand std::maps. The map uses intboth keys and values std::function. I associate methods with these functions. I am wondering if I can tell map.erase(i)if std :: will remove the function from memory or will I have a memory leak?

Here is a sample 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 erase test_map.erase(1); std::functionfrom memory?

+4
source share
2 answers

Although this is not good code, there is no memory leak; you save std::functionin std::mapby value (and not by pointer), so it std::map::erasewill call the destructor std::function.

, new std::function, delete any std::function.

+3

, lambdas :

fooobar.com/questions/81655/...

, r-, ( ..) std:: function. std::, std:: map erase (/ ).

+1

Source: https://habr.com/ru/post/1652064/


All Articles