Zayıf_ptr süresi sona eren bir haritada bir girdiye (boost :: zayıf_ptr türü) ne olacağını anlamak isterim. Haritadaki karşılık gelen giriş otomatik olarak silinir mi?Bir haritadaki süresi dolmuş bir zayıf_ptr'ye ne olur?
Anahtar bir tamsayıdır ve karşılık gelen değer bir zayıf_ptr'dir.
Örnek kod yazdım ama Java WeakSet dokümantasyonu weak_ptr süresi dolduğunda girişi kaldırılır söylüyor
#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;
}
derlemeye alamadım. Bu yüzden haritanın benzer (veya tanımlanmamış) bir davranış sergilediğini kontrol etmeyi düşünün.
Teşekkürler!
Std kapsayıcılarından herhangi biri, sona eren zayıf_ptr'ı otomatik olarak bir giriş olarak mı siliyor? – Maddy
@Maddy No. Bu makineyi kendiniz uygulayabilirsiniz (ilgili "zayıf_ptr" yi arayan haritayı referans gösteren özel bir işaretçi yazabilirsiniz) ancak bu son derece ağır bir ses çıkarır ve neredeyse kesinlikle istediğiniz gibi değildir. zaten yapmak – Barry