shared_ptr我最近在 lambda 中捕获 a 时在程序中遇到了一个奇怪的双重释放错误。我能够将其减少为以下最小示例:
#include <memory>
#include <functional>
struct foo {
std::function<void(void)> fun;
};
foo& get() {
auto f = std::make_shared<foo>();
// Create a circular reference by capturing the shared pointer by value
f->fun = [f]() {};
return *f;
}
int main(void) {
get().fun = nullptr;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
使用 GCC 12.2.0 和地址清理程序编译并运行它,会在 中产生双重释放std::function:
$ g++ -fsanitize=address -g -Wall -Wextra -o main main.cpp && ./main
=================================================================
==2401674==ERROR: AddressSanitizer: attempting double-free on 0x602000000010 in thread T0:
#0 …Run Code Online (Sandbox Code Playgroud)