c++ - 从 std::map 中删除 std::function lambda-wrapped 方法

标签 c++ c++11 memory-leaks lambda std-function

我正在使用 std::functionstd::map 创建一个回调系统。该映射使用 int 作为键,值为 std::function。我将方法绑定(bind)到这些函数中。我想知道如果我调用 map.erase(i),会从内存中删除 std::function,还是会发生内存泄漏?

下面是一些示例代码:

#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
  };                   

最后一个 test_map.erase(1); 是否从内存中删除了 std::function

最佳答案

虽然这不是好的代码,但没有内存泄漏;您按值(而不是指针)将 std::function 存储在 std::map 中,因此 std::map::erase 将调用 std::function 的析构函数。

换句话说,您不是新建任何std::function,因此您不需要删除任何std::function

关于c++ - 从 std::map 中删除 std::function lambda-wrapped 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39081405/

相关文章:

python - 使用 python 2.7 时内存泄漏

c++ - 编译器如何优化我们的代码?

c++ - 如何在没有 Python 调试库的情况下在 Debug模式下使用 Cmake/Visual Studio 构建 OpenCV

c++ - 获取包含时间间隔的字符串的最简单方法

c++ - 用原子做饱和运算

java - Solaris 9 : memory leak detection

c++ - 为 ORM C++ 实现 1 到 n 映射

c++ - 通过 constness 从结构传递到它的指针和引用成员

c++ - 什么是 "hint"?

c# - SQL Stored Proc 随着时间的推移消耗内存