gpt4 book ai didi

c++ - 将 std::shared_ptr 的容器 ( std::vector ) 过滤为 std::weak_ptr 的容器

转载 作者:行者123 更新时间:2023-11-30 02:46:18 25 4
gpt4 key购买 nike

我正在尝试过滤 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

关于c++ - 将 std::shared_ptr 的容器 ( std::vector ) 过滤为 std::weak_ptr 的容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23669954/

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