C++ 地图中过期的弱ptr会发生什么情况
我想了解弱ptr已过期的映射中的条目(类型为boost::弱ptr)会发生什么情况。地图中的相应条目是否会自动删除 键是一个整数,对应的值是一个弱\u ptr 我编写的示例代码,但无法编译C++ 地图中过期的弱ptr会发生什么情况,c++,shared-ptr,weak-ptr,C++,Shared Ptr,Weak Ptr,我想了解弱ptr已过期的映射中的条目(类型为boost::弱ptr)会发生什么情况。地图中的相应条目是否会自动删除 键是一个整数,对应的值是一个弱\u ptr 我编写的示例代码,但无法编译 #include <iostream> #include <map> #include <boost/enable_shared_from_this.hpp> using namespace std; class Foo : pu
#include <iostream>
#include <map>
#include <boost/enable_shared_from_this.hpp>
using namespace std;
class Foo : public boost::enable_shared_from_this<Foo> {
public:
Foo(int n = 0) : bar(n) {
std::cout << "Foo: constructor, bar = " << bar << '\n';
}
~Foo() {
std::cout << "Foo: destructor, bar = " << bar << '\n';
}
int getBar() const { return bar; }
boost::shared_ptr<Foo> inc_ref() {
return shared_from_this();
}
private:
int bar;
};
std::map<int, boost::weak_ptr<Foo> > mappy;
int main()
{
boost::shared_ptr<Foo> sptr(new Foo(1));
std::pair<std::map<int, boost::weak_ptr<Foo> >::iterator, bool> res =
mappy.insert(std::make_pair(10, sptr));
if (!res.second ) {
cout << "key already exists "
<< " with value " << (res.first)->second << "\n";
} else {
cout << "created key" << "\n";
}
std::cout << "sptr use count "<< sptr.use_count() << '\n';
sptr.reset();
std::cout << "sptr use count "<< sptr.use_count() << '\n';
std::map<int, boost::weak_ptr<Foo>, std::less<int> >::iterator map_itr = mappy.find(10);
if (map_itr == mappy.end()) {
cout << "Entry removed" << "\n";
} else {
cout << "Entry found: " << map_itr << "\n";
}
return 0;
}
#包括
#包括
#包括
使用名称空间std;
类Foo:public boost::从\u中启用\u共享\u{
公众:
Foo(int n=0):bar(n){
标准::cout
地图中的相应条目是否会自动删除
不,不存在。条目将继续存在。映射和共享\u ptr
是完全不相关的实体。最后一个共享\u ptr
的所有销毁都是释放内存
weak_ptr
的优点是weak_ptr
将能够知道共享_ptr
是否已被删除。这就是和成员函数的作用。但一旦过期,仍由您将其从映射中删除
地图中的相应条目是否会自动删除
当然不是。要实现这一点,std::map::find()
必须修改映射以删除过期元素,这是由于合同原因而无法做到的。尤其是const
版本。是否有任何std容器自动删除过期的弱ptr作为条目?@Maddy否。您可以自己实现该机制(编写一个自定义删除程序,保留对地图的引用,以搜索相应的弱\u ptr
,等等),但这听起来非常繁琐,几乎肯定不是您想要做的事情。