gpt4 book ai didi

c++ - map 中过期的 weak_ptr 会发生什么

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:18:09 27 4
gpt4 key购买 nike

我想了解 weak_ptr 已过期的映射中的条目(类型为 boost::weak_ptr)会发生什么。 map 中的相应条目是否会自动删除?

键是一个整数,对应的值是一个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 过期时,该条目将被删除。因此想到检查 map 是否表现出类似(或未定义)的行为。

谢谢!

最佳答案

Does the corresponding entry in the map get automatically deleted?

不,它没有。该条目将继续存在。映射和 shared_ptr 是完全不相关的实体。最后一个 shared_ptr 所做的所有破坏都是释放内存。

weak_ptr 的优点是weak_ptr 将能够知道shared_ptr 是否已被删除。这就是expired()lock()成员函数是为了。但是,一旦它过期,您仍然可以将其从 map 中删除。

关于c++ - map 中过期的 weak_ptr 会发生什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36132936/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com