我有一個boost :: multi_index_container與原始指針(是的,不是最好的主意,但遺憾的是我無法改變它...)和我需要刪除所有釋放內存的元素...如何擦除提升中的所有元素:multi_index應用「刪除器」
有沒有什麼辦法在boost :: multi_index_container中配置一個刪除函數並調用某種清除方法?
在此先感謝。
我有一個boost :: multi_index_container與原始指針(是的,不是最好的主意,但遺憾的是我無法改變它...)和我需要刪除所有釋放內存的元素...如何擦除提升中的所有元素:multi_index應用「刪除器」
有沒有什麼辦法在boost :: multi_index_container中配置一個刪除函數並調用某種清除方法?
在此先感謝。
是的。這個想法是使用一個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
在闡述@ 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";
}
謝謝您的回答......問題是,必須使用原始指針...這是一個古老的代碼,我不能改變...... – thamurath 2015-03-02 11:27:39
那麼答案是否定的。 (它怎麼可能是舊代碼,並且問題仍然是新的?) – sehe 2015-03-02 11:28:19
因爲原始指針在代碼中的許多點上都被使用......這些指針存儲在一個集合類容器中,但現在我需要通過另一個鍵來搜索...所以我試圖替換容器... – thamurath 2015-03-02 11:32:57