我怎样才能使用boost ::绑定没有明确的功能定义持有的boost :: 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功能到位的方法吗?像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
解决方案
您可以寻找“共享所有权”构造,这允许参考计数的内部指针。
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>
???
我不认为你想创建一个shared_ptr<int>
是围绕直接被诠释对象拥有的原始指针共享指针,作为诠释对象将删除_INT时,它超出范围(即使在该示例中它没有“新”吧!)。
您需要拿出一个明确的所有权/责任模式。
也许你可以提供你想达到什么不同的,更加逼真,例如?
不隶属于 StackOverflow