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 函数?就像 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
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 超出范围时删除它(即使在示例中它没有'新'它!)。

您需要提出一个明确的所有权/责任模型。

也许你可以提供一个不同的、更现实的例子来说明你想要实现的目标?

于 2010-03-16T10:47:14.580 回答