boost :: shared_ptr에서 boost :: bind를 명시 적 기능의 정의없이 어떻게 참조 할 수 있습니까?
-
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 기능을 제자리에 선언하는 방법이 있습니까? Lambda Expressions 또는 STH처럼? (재미있는 기능의 범위를 벗어난이 불쾌한 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
해결책
"공유 소유권"생성자를 찾고있을 수 있습니다.이를 통해 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>
???
나는 당신이 a를 만들고 싶다고 생각하지 않습니다 shared_ptr<int>
int 객체는 _int가 범위를 벗어날 때마다 _int를 삭제하기 때문에 int 객체가 직접 소유하는 원시 포인터 주변의 공유 포인터입니다 (예제에서는 '새'가 아니더라도!).
명확한 소유권/책임 모델을 제시해야합니다.
어쩌면 당신은 달성하려는 것의 다른, 더 현실적인 예를 제공 할 수 있습니까?
제휴하지 않습니다 StackOverflow