我正在尝试过滤一个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 constructed\n"; }
        explicit A(int a):a_val(a)      { std::cout << "A argument constructed\n";  }
        A(const A& other)               { a_val = other.a_val ; std::cout << "A copy constructed\n";  }
        A& operator=(const A& other)    { a_val = other.a_val ; std::cout << "A copy assigned\n";   return *this; }
        ~A()                            { std::cout << "A is destroyed\n"; }



        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 of this

10-01 23:16