我有以下代码:
- void MyClass::onOpenModalBtnClicked()
- {
- uiManager->load(L"data/ui/testmodal.json");
- std::shared_ptr<UIElement> modal = uiManager->getElementById("loginModal");
- if(modal)
- {
- modal->getElementById("closeButton")->onClicked = [modal]() {
- modal->hide();
- };
- }
- }
这个工作正常,当点击按钮时,模态是关闭的,onClicked是一个std ::函数.
我也在我的应用程序的开头有这个:
- #if defined(DEBUG) | defined (_DEBUG)
- _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
- #endif
这会在应用程序终止时打印出内存泄漏.
使用上面的代码,我会收到很多内存泄漏,如果我将代码更改为下面的代码,它们都会消失:
- void MyClass::onOpenModalBtnClicked()
- {
- uiManager->load(L"data/ui/testmodal.json");
- std::shared_ptr<UIElement> modal = uiManager->getElementById("loginModal");
- if(modal)
- {
- modal->getElementById("closeButton")->onClicked = [this]() {
- uiManager->getElementById("loginModal")->hide();
- };
- }
- }
我假设传递shared_ptr通过值将引用计数增加1,然后该引用永远不会超出范围,或者在报告了mem泄漏之后超出范围.所以我试图在我使用shared_ptr之后调用lambda里面的reset,但是我得到这个编译器的错误:
错误1错误C2662:’void std :: shared_ptr< _Ty> :: reset(void)throw()’:不能将’this’指针从’const std :: shared_ptr< _Ty>到'std :: shared_ptr< _Ty> &安培;”
所以问题是如何使用捕获的模态,而不是得到那些内存泄漏?
编辑:
所以我通过向lambda添加mutable来摆脱编译错误.
- if(modal)
- {
- modal->getElementById("closeButton")->onClicked = [modal]() mutable {
- modal->hide();
- modal.reset();
- };
- }