std::function
とstd::map
を使用してコールバックシステムを作成しています。マップはint
をキーとして使用し、値はstd::function
です。私はそれらの関数にメソッドを束縛します。 map.erase(i)
と呼ぶと、メモリからstd :: functionを削除するのだろうか?それともメモリリークがありますか?ここでstd :: functionラムダラップされたメソッドをstd :: mapから削除する
は、いくつかのサンプルコードです:
#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
を削除していますか?
このコードで唯一注意すべきことは、 'delete test;'と 'test_map.erase(1);'の間にあります。ここでは、ラムダがぶら下がっている 'this'ポインタを参照しています。この例では、これは有害ではありませんが、「成長中の」アプリケーションまたはマルチスレッドのアプリケーションでは未定義の動作が開始される可能性があります。一般的に、ラムダの代わりにマップにTestClassを格納することで解決できる、コード内に奇妙な生涯の問題があります。 – stefaanv