C++ shared_ptr 绑定映射转换段错误

C++ shared_ptr bind map transform segfault

当我 运行 这段代码时出现段错误:

#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));
  }
}

我在 c++11 模式下使用 g++ 4.8.2 进行编译。

当我打印 shared_ptr 的使用计数时,似乎每次 for 循环 运行s.

它都会减 1

您可能在 bind(&pair<int, shared_ptr<int>>::second, _1)) 中获得转换,因为它是 pair<int const, shared_ptr<int>> 存储在地图中的内容(注意 const 键类型)。

虽然我很惊讶它编译没有错误。

试试这些:

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))

你的问题似乎是 second 不是一个函数(它是一个成员变量),所以它不能与 bind.

绑定

你可以试试

transform(container.begin(), container.end(), vec.begin(), [](pair<int, shared_ptr<int>> x) { return x.second; });

transform(container.begin(), container.end(), vec.begin(), bind(&_2nd, _1));

您之前定义的地方

shared_ptr<int> _2nd(const pair<int, shared_ptr<int>>& x) { return x.second; }

那行得通。 Live example at Coliru...