2014-04-01 97 views
0

在我的應用程序中使用指針,我有以下類別:用的boost :: bimap的

class transaction 
{ 
public: 
    ..... 
} 

class src_transaction: public transaction 
{ 
public: 
    ..... 
} 

class dst_transaction: public transaction 
{ 
public: 
    ..... 
} 

我想構建一個bimap的,這將需要一個整數和指針要麼src_transaction或dst_transaction。

如何使用Boost庫來做到這一點? 我是否應該將「class transaction」聲明爲enable_shared_from_this?如果是這樣,它應該是unqiue_ptr或shared_ptr? 因爲我想要做的任何src_transaction或dst_transaction內BIAMP一些操作如下:

bimap.inset(12, "Pointer to the current transaction i.e. from the same class"); 

回答

2

你應該嘗試這樣的事:

#include <iostream> 
    #include <boost/bimap.hpp> 
    #include <boost/shared_ptr.hpp> 
    #include <boost/make_shared.hpp> 


    using namespace std; 

    class Base{ 

    public: 
     Base(int val):_value(val){} 
     int _value; 

    }; 


    class Derv1:public Base{ 

     public: 
     Derv1(int val):Base(val){} 

    }; 


    class Derv2:public Base{ 

     public: 
     Derv2(int val):Base(val){} 

    }; 

    //typedef boost::bimap< int,Base* > bm_type; 
    typedef boost::bimap< int,boost::shared_ptr<Base> > bm_type; 
    bm_type bm; 

    int main() 
    { 

    // bm.insert(bm_type::value_type(1,new Derv1(1))); 
    // bm.insert(bm_type::value_type(2,new Derv2(2))); 

    bm.insert(bm_type::value_type(1,boost::make_shared<Derv1>(1))); 
    bm.insert(bm_type::value_type(2,boost::make_shared<Derv2>(2))); 

     cout << "There are " << bm.size() << "relations" << endl; 

     for(bm_type::const_iterator iter = bm.begin(), iend = bm.end(); 
      iter != iend; ++iter) 
     { 
     // iter->left : data : int 
     // iter->right : data : Base* 

     cout << iter->left << " <--> " << iter->right->_value << endl; 
     } 

    } 
+0

謝謝,我已經做到了,但我看到了一些實現在set和map STL中使用boost :: shared_ptr和unique_ptr,與你做了什麼有什麼不同? – IoT

+0

@ HA-AS好的,我剛剛使用普通的簡單指針,如果你關心內存的釋放,那麼使用共享指針會很好。即使其他指針正在使用,唯一指針也會具有刪除內存的行爲。 – Nik

+0

你能給我一個共享指針的例子嗎? – IoT