问题描述:

I am trying to filter a container of shared_ptr and trying to save the filtered content in a non owning container ( of weak_ptr ). The program found below crashes. Can some one see what am I missing ?

 #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";

}

网友答案:

This is the problem: std::shared_ptr< A > current_node(this);. You just can't do that by default, this has a lifetime of its own. See: std::shared_ptr of this

相关阅读:
Top