如何擦除提升中的所有元素:multi_index应用"deleter"

How to erase all elements in a boost:multi_index applying a "deleter"

本文关键字:元素 multi index deleter 应用 何擦除 擦除      更新时间:2023-10-16

我有一个带有原始指针的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";
}