将std::shared_ptr类型的容器(std::vector)过滤为std::weak_ptr类型的容器

Filtering a container ( std::vector ) of std::shared_ptr to a container of std::weak_ptr

本文关键字:std 类型 ptr 过滤 weak shared vector      更新时间:2023-10-16

我试图过滤shared_ptr的容器,并试图将过滤的内容保存在一个非拥有的容器(weak_ptr)。下面的程序崩溃了。有人能看出我错过了什么吗?

    #include <memory>
    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <functional>
    #include <boost/bind.hpp>
    struct A
    {
        int a_val;
        explicit A():a_val(0)           { std::cout << "A default constructedn"; }
        explicit A(int a):a_val(a)      { std::cout << "A argument constructedn";  }
        A(const A& other)               { a_val = other.a_val ; std::cout << "A copy constructedn";  } 
        A& operator=(const A& other)    { a_val = other.a_val ; std::cout << "A copy assignedn";   return *this; } 
        ~A()                            { std::cout << "A is destroyedn"; }

        struct a_visitor
        {
            std::vector < std::weak_ptr < A >  > filtered_a;
            a_visitor() { filtered_a.resize(0); }
            void operator() (std::shared_ptr < A > a_ref)
            {
                if(a_ref->a_val % 2 )
                    filtered_a.push_back(a_ref);
            }
        };
        std::function < void ( std::shared_ptr < A > ) > a_visit_function;

        void visit_vector ( a_visitor *visitor)
        {
            a_visit_function = boost::bind(&a_visitor::operator(), visitor, _1);
            std::shared_ptr< A > current_node(this);
            a_visit_function(current_node);
        }
    };
    int main(void)
    {
        std::vector < std::shared_ptr < A > > a_array;
        for(int i=10;i<20;i++)
        {
            a_array.emplace_back(std::make_shared<A>(A(i)));
        }
        std::cout << "--------------------------n";
        std::for_each(a_array.begin(), a_array.end(), ([&]( std::shared_ptr<A> &a_ref){
            std::cout << a_ref << " : " << a_ref->a_val << std::endl;
        }));
        std::cout << "--------------------------n";
        A::a_visitor visitor;
        std::for_each(a_array.begin(), a_array.end(), ([&](std::shared_ptr < A > a_ref){
            a_ref->visit_vector(&visitor);
        }));
        std::cout << "--------------------------n";
        std::for_each(visitor.filtered_a.begin(), visitor.filtered_a.end(), ([&](std::weak_ptr<A> &a_ref){
            std::cout << a_ref.lock()->a_val << std::endl;
        }));
        std::cout << "--------------------------n";
    }

这就是问题所在:std::shared_ptr< A > current_node(this);。默认情况下你不能这么做,this有自己的生命周期。参见:std::shared_ptr