簡體   English   中英

如何在不使用顯式函數定義的情況下使用boost :: bind在boost :: shared_ptr中保存引用?

[英]How can i hold reference in boost::shared_ptr using boost::bind without definition of explicit function?

我想保留對對象的引用,以便它不會在綁定函數中被刪除,但不使用輔助函數。

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函數,必須在fun函數的范圍之外聲明)我嘗試了幾次,但都沒有編譯過:)

好的,這是更詳細的示例:

#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

您可能正在尋找“共享所有權”構造函數,這允許引用計數內部指針。

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);
}

您在這里想要做什么讓我有些困惑。

是fun()應該返回boost::shared_ptr<int>還是boost::shared_ptr<Int>

我不認為您要創建一個shared_ptr<int> ,它是由Int對象直接擁有的原始指針周圍的共享指針,因為只要Int對象超出范圍,Int對象就會刪除_int(即使在示例中,它不是“新的”!)。

您需要提出一個明確的所有權/責任模型。

也許您可以提供一個不同的,更現實的示例來說明您要實現的目標?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM