C++ C++;共享\u ptr绑定映射转换SEGFULT
当我运行此代码时,我得到一个segfault:C++ C++;共享\u ptr绑定映射转换SEGFULT,c++,c++11,segmentation-fault,bind,shared-ptr,C++,C++11,Segmentation Fault,Bind,Shared Ptr,当我运行此代码时,我得到一个segfault: #include <memory> #include <algorithm> #include <map> #include <vector> #include <functional> using namespace std; using namespace std::placeholders; int main(){ map<int, shared_ptr<
#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));
}
}
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
使用名称空间std::占位符;
int main(){
地图容器;
容器[5]=使_共享(7);
对于(int i=0;i<10;++i){
向量向量(container.size());
转换(container.begin()、container.end()、vec.begin(),
绑定(&pair::second,_1));
}
}
我正在c++11模式下使用g++4.8.2进行编译
当我打印共享\u ptr的使用计数时,似乎每次for循环运行时它都会减少1。您可能在
bind(&pair::second,_1))
中得到转换,因为它是存储在映射中的pair
(注意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))
bind(&pair::second,_1))
绑定(&map::value\u type::second,_1))
绑定(&decltype(容器)::值\类型::秒,\ 1))
您的问题似乎是second
不是一个函数(它是一个成员变量),因此它不能与bind
绑定
你可以试试
transform(container.begin(), container.end(), vec.begin(), [](pair<int, shared_ptr<int>> x) { return x.second; });
您以前定义的位置
shared_ptr<int> _2nd(const pair<int, shared_ptr<int>>& x) { return x.second; }
shared_ptr_2nd(const pair&x){return x.second;}
那就行了 不确定要实现什么,但这里有一个修改(使用C++11 lambdas)不会崩溃:transform(container.begin(),container.end(),vec.begin(),[](const std::pair&p){return p.second;});*container.begin()的类型不是pair,而是pairCheck out:f-可调用对象(函数对象、函数指针、函数引用、成员函数指针或数据成员指针),将绑定到某些参数
shared_ptr<int> _2nd(const pair<int, shared_ptr<int>>& x) { return x.second; }