[英]Filtering a container ( std::vector ) of std::shared_ptr to a container of std::weak_ptr
我試圖過濾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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.