2010-03-16 50 views
0

我想持有引用對象,所以它不會被綁定函數中刪除,但不使用幫助函數。如何在boost :: shared_ptr中使用boost :: bind而不使用顯式函數的定義來保存引用?

struct Int 
{ 
    int *_int; 
    ~Int(){ delete _int; } 
}; 

void holdReference(boost::shared_ptr<Int>, int*) {} // helper 

boost::shared_ptr<int> fun() 
{ 
    boost::shared_ptr<Int> a (new Int); 
    // I get 'a' from some please else, and want to convert it 
    a->_int = new int; 

    return boost::shared<int>(a->_int, boost::bind(&holdReference, a, _1)); 

} 

有沒有辦法來聲明holdReference函數?像lambda表達式一樣? (不使用這個討厭的holdReference功能,有樂趣的功能範圍之外聲明) 我有幾次嘗試,但他們的非編:)

好吧,這裏是更詳細的例子:

#include <boost/shared_ptr.hpp> 
#include <boost/bind.hpp> 

// the case looks more or less like this 
// this class is in some dll an I don't want to use this class all over my project 
// and also avoid coppying the buffer 
class String_that_I_dont_have 
{ 
    char * _data; // this is initialized in 3rd party, and released by their shared pointer 

public: 
    char * data() { return _data; } 
}; 


// this function I created just to hold reference to String_that_I_dont_have class 
// so it doesn't get deleted, I want to get rid of this 
void holdReferenceTo3rdPartyStringSharedPtr(boost::shared_ptr<String_that_I_dont_have>, char *) {} 


// so I want to use shared pointer to char which I use quite often 
boost::shared_ptr<char> convert_function(boost::shared_ptr<String_that_I_dont_have> other) 
// 3rd party is using their own shared pointers, 
// not the boost's ones, but for the sake of the example ... 
{ 
    return boost::shared_ptr<char>( 
     other->data(), 
     boost::bind(
      /* some in place here instead of holdReference... */ 
      &holdReferenceTo3rdPartyStringSharedPtr , 
      other, 
      _1 
     ) 
    ); 
} 

int main(int, char*[]) { /* it compiles now */ } 

// I'm just looking for more elegant solution, for declaring the function in place 
+0

這不會編譯。請發佈您的實際代碼並解釋您想要實現的目標 – 2010-03-16 10:54:39

回答

1

您可能正在尋找「共享所有權」的構造函數,這允許ref計數一個內部指針。

struct Int 
{ 
    int *_int; 
    ~Int(){ delete _int; } 
}; 

boost::shared_ptr<int> fun() 
{ 
    boost::shared_ptr<Int> a (new Int); 
    a->_int = new int; 

    // refcount on the 'a' instance but expose the interior _int pointer 
    return boost::shared_ptr<int>(a, a->_int); 
} 
+0

Yeap,就是這樣:) – pprzemek 2010-03-16 21:14:40

0

我對你在這裏試圖做什麼感到困惑。

很有趣()應該返回boost::shared_ptr<int>boost::shared_ptr<Int> ???

我不認爲你想創建一個shared_ptr<int>是一個共享指針,它是一個直接由Int對象擁有的原始指針,因爲當Int對象超出作用域時它將刪除_int(even儘管在這個例子中它不是'新'的!)。

你需要想出一個清晰的所有權/責任模型。

也許你可以提供一個不同的,更現實的例子,你試圖實現什麼?

相關問題