Boost logo

Boost Users :

From: Mark Santaniello \(AMD\) (b-marks_at_[hidden])
Date: 2005-11-16 03:50:20


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;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net