Boost logo

Boost Users :

Subject: Re: [Boost-users] [Bind] Unexpected behavior when binding const char* to function
From: Piotr Jachowicz (pjachowi_at_[hidden])
Date: 2010-04-27 17:35:19


On 27 April 2010 20:55, Michael Caisse <boost_at_[hidden]> wrote:
> Piotr -
>
> I don't think this is "unexpected behavior" to most. You have *not*
> bound abc. You have bound a pointer. What that pointer points to may
> change and when you use the pointer it may very well point to something
> different than at the time of the bind.
>
> This isn't "unexpected". Your bind is to a pointer. You need to either
> ensure that the value pointed at doesn't change or you can pass an object
> containing the data itself.

I've called it "unexpected", because f1() and f2() in code below
behaves differently:

void echo1(const char* c) {
  cout << c << '\n';
}

void echo2(const string& s) {
  cout << s << '\n';
}

int main() {
  boost::function<void ()> f1 = boost::bind(echo1, "abc"); //ups!
binding to address of temporary
  boost::function<void ()> f2 = boost::bind(echo2, "abc"); //ok, bind
copies temporary string("abc")
  f1(); f2();
}

Incoming book "How to code with C++0x and not commit suicide" will
have to contain advise "When you bind, ensure that function signature
have no pointers; otherwise you are in trouble".

To be serious: library should naturally promote its proper usage. Code
like "boost::bind(echo1, "abc")" looks natural, does not emit any
warning, and is dangerous. Cases like that promote stereotype "It's
better to avoid Boost because it contains many traps". I think that
compiler warning would save hours of debugging for many programmers.

>
>
> michael
>
> --
>
> ----------------------------------
> Michael Caisse
> Object Modeling Designs
> www.objectmodelingdesigns.com
>
>
> _______________________________________________
> Boost-users mailing list
> Boost-users_at_[hidden]
> http://lists.boost.org/mailman/listinfo.cgi/boost-users
>

-- 
Piotr Jachowicz

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