I've been using std::function with GCC 5.1 in c++11 mode for registering some callbacks in a program. The program also loads in a shared library as a plugin, and is also allowed to register callbacks. Everything works as expected, but upon terminating the program segfaults. I traced the problem to the std::function destructor, which is using, in my case, an invalid _M_manager handle (which causes the segfault). Based on some further testing, it seems the handle is invalidated by the plugin being unloaded before the std::function destructor is called. If I switch the order of destruction/unloading, the program finishes without problems. I was able to reproduce the problem in a simple setup, which I'm inlining below. Simply run the Makefile, and then run the `test` executable. It should segfault (at least it does on my amd64 Linux system). Is std::function supposed to be that sensitive to shared libraries? Am I missing something from the documentation that explains this behavior? Thank you for any insight on the issue! Sincerely, Gabriel E. Marcano ------------------------------ Makefile: CXXFLAGS = -Wall -Wextra -pedantic -std=c++11 -g -O0 -fPIC .PHONY: clean all all: test shared.so test: main.o $(CXX) $(CXXFLAGS) $^ -o $@ -ldl shared.so: shared.o $(CXX) $(CXXFLAGS) $^ -o $@ -fPIC -shared clean: rm -f *.o test shared.so ------------------------------ main.cpp: #include <functional> #include <dlfcn.h> void shared(std::function<void()>&); int main() { typedef void(*sh_f)(std::function<void()>&); void* lib = dlopen("./shared.so", RTLD_NOW); sh_f sh = (sh_f)dlsym(lib, "load"); std::function<void()> f; sh(f); dlclose(lib); return 0; } ------------------------------ shared.cpp: #include <functional> void shared() {} extern "C" void load(std::function<void()>& fun) { fun = shared; } ------------------------------