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

标签 c++ shared-ptr weak-ptr

我想了解 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/

相关文章:

c++:在函数参数列表中使用或不使用 namespace

c++ - 比较两个 multimaps c++

c++ - 从 std::shared_ptr 窃取位

c++ - 如何将 double 转换为 float 指针?

c++ - #define 和 CUDA

c++ - 检查 shared_ptr 的容器是否包含指针?

c++ - 智能指针和构造函数异常

c++ - 在 std::set 或 std::map 的键中使用 weak_ptr 是否安全

c++ - 是否存在无法锁定(提升为 shared_ptr)的 weak_ptr 之类的东西?如果不是,为什么?

c++ - 关于 "circular reference",我使用了 weak_ptr 但内存泄漏仍然发生