如何擦除提升中的所有元素:multi_index应用"deleter"
How to erase all elements in a boost:multi_index applying a "deleter"
我有一个带有原始指针的boost::multi_index_container(是的,不是最好的主意,但遗憾的是我无法更改它…),我需要删除所有释放内存的元素。。。
有没有办法在boost::multi_index_container中配置delete函数并调用某种clear方法?
提前谢谢。
是。这个想法是使用RAII容器,就像智能指针一样。
通过这种方式,您可以确保删除程序在擦除项目时运行。
Coliru现场演示
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <iostream>
using namespace boost::multi_index;
struct Demo {
Demo(int id) : id(id) {}
int get_id() const { return id; }
~Demo() { std::cout << "some kind of deleter runs :)n"; }
private:
int id;
};
typedef multi_index_container<boost::shared_ptr<Demo>,
indexed_by<
hashed_unique<const_mem_fun<Demo, int, &Demo::get_id>>>
> HostContainer;
int main()
{
{
HostContainer testHosts;
testHosts.insert(boost::make_shared<Demo>(42));
}
std::cout << "donen";
}
打印
some kind of deleter runs :)
done
详细说明@Sehe的答案,您可以有一个隐式接受原始指针的智能指针,这样用户代码就不需要更改:
Coliru现场演示
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/mem_fun.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/make_shared.hpp>
#include <iostream>
using namespace boost::multi_index;
template<typename T>
struct implicit_shared_ptr:boost::shared_ptr<T>
{
implicit_shared_ptr(T* p):boost::shared_ptr<T>(p){}
};
struct Demo {
Demo(int id) : id(id) {}
int get_id() const { return id; }
~Demo() { std::cout << "some kind of deleter runs :)n"; }
private:
int id;
};
typedef multi_index_container<
implicit_shared_ptr<Demo>,
indexed_by<
hashed_unique<const_mem_fun<Demo, int, &Demo::get_id>>>
> HostContainer;
int main()
{
{
HostContainer testHosts;
testHosts.insert(new Demo{42});
}
std::cout << "donen";
}
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- C++如何通过用户输入删除列表元素
- lower_bound()返回最后一个元素
- 基于多个条件处理地图中的所有元素
- 调整大小后指向元素值的指针unordered_map有效?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 使用函数"remove"删除重复元素
- 具有最大子序列大小的序列,每个元素都相同
- 如何将两个不同矢量的同一位置的两个元素组合在一起
- 如何将元素添加到数组的线程安全函数?
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何通过 getter 函数删除矢量的元素?
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- 从控制台中删除最后打印的元素
- 擦除while循环中迭代的元素