All,
I'm trying to use lambda and shared_ptr together, but I'm running into a
problem. Please see the code below.
I'd like the lambda-generated functor to hold the shared_ptr by value,
such that its ref count is incremented. This doesn't seem to be
happening. Instead, the shared_ptr is deleted when foo() returns,
resulting in undefined behavior.
What am I doing wrong?
Thanks,
Mark
#include
#include
#include
#include <iostream>
using namespace std;
using namespace boost::lambda;
template< typename T >
boost::function foo( T n_ )
{
//Works, but leaks n
//T *n = new T( n_ );
//Doesn't work
boost::shared_ptr<T> n( new T(n_) );
return ( *n += _1 );
}
int main()
{
// start with one
boost::function accum = foo(1);
cout << accum(2) << endl;
cout << accum(10) << endl;
// start with zero
boost::function accum2 = foo(0);
cout << accum2(6) << endl;
cout << accum2(2) << endl;
}