将std::shared_ptr类型的容器(std::vector)过滤为std::weak_ptr类型的容器
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 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
相关文章:
- 如何获取std::result_of函数的返回类型
- 如何在c++迭代器类型中包装std::chrono
- 在C++中对T*类型执行std::move的意外行为
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在一个模板函数中,若输入的类型是enum类,我该如何使用std::underlying_type
- 为什么 std::optional::operator=(U&&) 要求你是非标量类型?
- std::visit无法识别类型
- 哪些类型可以转换为std::any
- 从类型std::函数传递变量失败,尽管调用方期望的类型完全相同
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- <Windows>为什么 std::thread::native_handle 返回类型为"long long unsigned int"的值,而不是 void*(又名 HANDLE)?
- r语言 - C++ 类型为"const std ::?
- C++中"std::sort"比较器的不同类型
- C++11 中不同类型的对象的 std::array 的替代方案
- 检查某些类型是否是模板类 std::optional 的实例化
- clion 无法解析 std 类型
- 使用 std 类型的 ADL 无法找到运算符
- 为什么 std 类型不提供来自分配器不同源的转换构造函数/赋值
- 哪些 std 类型在移动构造函数中用作 arg 后保证为空/空
- Qt -混合Qt和std:: c++类型