Boost logo

Boost Users :

Subject: Re: [Boost-users] [Lambda] Lost in lambda land!
From: Ovanes Markarian (om_boost_at_[hidden])
Date: 2010-03-24 07:50:24


On Wed, Mar 24, 2010 at 11:29 AM, Robert Jones <robertgbjones_at_[hidden]>wrote:

> On Wed, Mar 24, 2010 at 9:19 AM, Ovanes Markarian <om_boost_at_[hidden]>wrote:
>
>>

> Ok, I know I'm having an aberrant moment here, but remind me why a
> temporary
> can't be passed as a non-const reference.
>

Because ISO C++ Standard 2003 prohibits it and explicitly states that the
lifetime of a temporary can be extended when it is bound to a
const-reference. I don't know the exact paragraph, nor have the access to
the Standard right now, but I clearly remember having read it. There is even
an example how long the temporary lives when bound to the const-reference.
The situation will change with the moving semantics and rvalue references in
the upcoming standard C++0x. If you really need to modify the internal
object state you could introduce mutable data members. Those can be changed
from const-qualified member functions. But think twice if you really need
it...

Getting back to the previous example the code looks as:

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/construct.hpp>
#include <algorithm>
#include <vector>

struct A
{
      A(int i) : i_(i) {}

      void f()const
      {
         i_ = 20;
      }

private:
     mutable int i_;
};

int main( )
{
      using namespace boost::lambda;

      std::vector< int > v;
      std::for_each( v.begin( ), v.end(), bind(&A::f,
bind<A>(constructor<A>(), _1)));
}

Regards,
Ovanes



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