0

バインド関数で削除されないようにオブジェクトへの参照を保持したいのですが、ヘルパー関数を使用しません。

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関数を適切に宣言する方法はありますか?ラムダ式やsthのように?(この厄介な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
4

2 に答える 2

1

「共有所有権」コンストラクターを探している可能性があります。これにより、参照が内部ポインターをカウントできます。

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);
}
于 2010-03-16T15:35:02.413 に答える
0

あなたがここで何をしようとしているのか、私は少し混乱しています。

fun() は返されるはずですboost::shared_ptr<int>か、それともboost::shared_ptr<Int>???

shared_ptr<int>Int オブジェクトがスコープ外になるたびに _int を削除するため、Int オブジェクトが直接所有する生のポインターの周りに共有ポインターである aを作成したいとは思わない(例では'new' しませんでした!)。

明確な所有権/責任モデルを考え出す必要があります。

おそらく、あなたが達成しようとしていることの別の、より現実的な例を提供できますか?

于 2010-03-16T10:47:14.580 に答える