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 13:53:01


Hello,

Igor R <boost.lists <at> gmail.com> writes:

>
> > function<void ()> f = boost::bind(echo, s.c_str());
>
> The expression x.c_str() returns a pointer that becomes invalid as
> soon as any non-const member function of std::string is called for x.

I know reason behind. But use is right to think "I've bind >>abc<<.
Binder should store it and use on f() invocation".

In real code the situation could be even worse - if f can be stored
for future use and invoked when s has already been destroyed.

Passing string instead of const char* behaves exactly how expected

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

int main() {
  string s2 = "abc";
  function<void ()> f2 = boost::bind(echo2, s2);
  s2 = "xyz";
  f();
}

My point is that difference between binding to echo and echo2 (string
vs. const char*) should not lead do different behavior. Otherwise user
has to be very careful on signature of bind'ed function. Binding to
function that accepts const char* leads to very strange results. It
resembles me infamous scanf().

> _______________________________________________
> Boost-users mailing list
> Boost-users <at> lists.boost.org
> 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