lambda and shared_ptr?

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 <boost/lambda/lambda.hpp> #include <boost/function.hpp> #include <boost/shared_ptr.hpp> #include <iostream> using namespace std; using namespace boost::lambda; template< typename T > boost::function<T(T)> 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<int(int)> accum = foo(1); cout << accum(2) << endl; cout << accum(10) << endl; // start with zero boost::function<int(int)> accum2 = foo(0); cout << accum2(6) << endl; cout << accum2(2) << endl; }

Mark Santaniello (AMD) wrote:
template< typename T > boost::function<T(T)> 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 );
I think that you need to wrap n in boost::lambda::constant: return *constant(n) += _1; Without it, *n is evaluated immediately.
}
participants (2)
-
Mark Santaniello (AMD)
-
Peter Dimov