![](/img/trans.png)
[英]What is diffrence between lock() and expired()? weak_ptr C++
[英]What happens to an expired weak_ptr in a map
我想了解weak_ptr已过期的地图中的条目(类型为boost :: weak_ptr)会发生什么。 地图中的相应条目是否会自动删除?
键是整数,对应的值是weak_ptr。
我编写的示例代码,但无法编译
#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;
}
Java中的WeakSet文档说明当weak_ptr到期时该条目被删除。 因此,想一想检查地图是否表现出类似(或未定义)的行为。
谢谢!
地图中的相应条目是否会自动删除?
当然不。 要实现这一点, std::map::find()
必须修改地图,删除过期的元素,由于合同而无法做到这一点。 特别是const
版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.