Search code examples
c++c++11segmentation-faultbindshared-ptr

C++ shared_ptr bind map transform segfault


I get a segfault when I run this code:

#include <memory>
#include <algorithm>
#include <map>
#include <vector>
#include <functional>

using namespace std;
using namespace std::placeholders;    

int main(){
  map<int, shared_ptr<int>> container;
  container[5] = make_shared<int>(7);

  for (int i = 0; i < 10; ++i) {
    vector<shared_ptr<int>> vec(container.size());

    transform(container.begin(), container.end(), vec.begin(),
              bind(&pair<int, shared_ptr<int>>::second, _1));
  }
}

I'm compiling with g++ 4.8.2 in c++11 mode.

When I print the use count of the shared_ptr, it seems it gets decremented by 1 each time the for loop runs.


Solution

  • You are probably getting conversions here in bind(&pair<int, shared_ptr<int>>::second, _1)) because it is pair<int const, shared_ptr<int>> what is stored in the map (note const on the key type).

    Although I am surprised it compiles without an error.

    Try any of these:

    bind(&pair<int const, shared_ptr<int>>::second, _1))
    bind(&map<int, shared_ptr<int>>::value_type::second, _1))
    bind(&decltype(container)::value_type::second, _1))