【发布时间】:2015-03-02 10:54:28
【问题描述】:
我有一个带有 原始指针 的 boost::multi_index_container(是的,这不是最好的主意,但遗憾的是我无法更改它...),我需要删除所有释放内存的元素。 ..
有没有办法在 boost::multi_index_container 中配置一个删除函子并调用某种 clear 方法?
提前致谢。
【问题讨论】:
标签: c++ boost boost-multi-index
我有一个带有 原始指针 的 boost::multi_index_container(是的,这不是最好的主意,但遗憾的是我无法更改它...),我需要删除所有释放内存的元素。 ..
有没有办法在 boost::multi_index_container 中配置一个删除函子并调用某种 clear 方法?
提前致谢。
【问题讨论】:
标签: c++ boost boost-multi-index
是的。这个想法是使用 RAII 容器,例如智能指针。
这样您就可以确保在删除项目时运行删除程序。
#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 << "done\n";
}
打印
some kind of deleter runs :)
done
【讨论】:
std::set 也没有erase_and_delete 成员。也许你对 Boost Intrusive 很感兴趣boost.org/doc/libs/1_57_0/doc/html/intrusive/…
详细说明@Sehe 的答案,您可以拥有一个隐式接受原始指针的智能指针,这样用户代码就无需更改:
#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 << "done\n";
}
【讨论】: