std::function and shared object libraries

Gabriel Marcano
Sat Jun 13 03:40:00 GMT 2015

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!


Gabriel E. Marcano


CXXFLAGS = -Wall -Wextra -pedantic -std=c++11 -g -O0 -fPIC

.PHONY: clean all

all: test

test: main.o
$(CXX) $(CXXFLAGS) $^ -o $@ -ldl shared.o
$(CXX) $(CXXFLAGS) $^ -o $@ -fPIC -shared

rm -f *.o test



#include <functional>
#include <dlfcn.h>

void shared(std::function<void()>&);

int main()
  typedef void(*sh_f)(std::function<void()>&);
  void* lib = dlopen("./", RTLD_NOW);
  sh_f sh = (sh_f)dlsym(lib, "load");
  std::function<void()> f;
  return 0;


#include <functional>

void shared()

extern "C" void load(std::function<void()>& fun)
  fun = shared;


More information about the Gcc-help mailing list