どのように私は、明示的な関数の定義なしブースト::バインドを使用してブースト:: shared_ptrの参照を保持することができますか?
-
20-09-2019 - |
質問
私はオブジェクトへの参照を保持したいので、それはしかし、ヘルパー関数を使用せずに、バインド機能では削除されません。
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機能を、使用しません) 私はいくつかの試みがあったが、それらの非はコンパイル:)
[OK]を、ここではより詳細な例である:
#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
解決
あなたは「共有所有権」コンストラクタを探している可能性があり、これは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);
}
他のヒント
私は少しあなたがここでやろうとしているもので混乱しています。
楽しい()
???boost::shared_ptr<int>
またはboost::shared_ptr<Int>
を返すことになっています
私もかかわらず、(あなたはintオブジェクトが_intを削除しますと、それはスコープの外に出るたび、直接intオブジェクトによって所有される生のポインタの周りに共有ポインタであるshared_ptr<int>
を作成したいとは思いません例ではそれが「新しい」しませんでした!)。
あなたは明確な所有権/責任モデルを考え出す必要があります。
おそらく、あなたはあなたが達成しようとしているかの異なった、より現実的な例を提供することができますか?
所属していません StackOverflow