2015-03-02 119 views

回答

0

是的。這個想法是使用一個RAII容器,就像一個智能指針。

通過這種方式,您可以確保刪除程序在物品被刪除時運行。

Live Coliru Demo

#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 
+0

謝謝您的回答......問題是,必須使用原始指針...這是一個古老的代碼,我不能改變...... – thamurath 2015-03-02 11:27:39

+0

那麼答案是否定的。 (它怎麼可能是舊代碼,並且問題仍然是新的?) – sehe 2015-03-02 11:28:19

+0

因爲原始指針在代碼中的許多點上都被使用......這些指針存儲在一個集合類容器中,但現在我需要通過另一個鍵來搜索...所以我試圖替換容器... – thamurath 2015-03-02 11:32:57

0

在闡述@ Sehe的答案,你可以有一個隱含接受裸指針,以便用戶代碼不需要改變一個智能指針:

Live Coliru Demo

#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"; 
}