|
Boost Users : |
Subject: Re: [Boost-users] [Bind] Unexpected behavior when binding constchar* to function
From: Piotr Jachowicz (pjachowi_at_[hidden])
Date: 2010-04-28 17:19:39
On 28 April 2010 11:04, Joseph Gauterin <joseph.gauterin_at_[hidden]> wrote:
>>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.
>
> Passing a std::string vs a const char* to boost::bind should have as
> close as possible to same behaviour as passing that parameter to a
> normal C++ function..
>
>>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.
> That code is safe - the lifetime of string literals is the lifetime of
> the program.
Good point! Yes, it's my mistake. I should have write something like that:
void f1(const string& s) {
cout << s << '\n';
}
function<void ()> make1(const string& s) {
return bind(f1, s); //ok, bind copies s
}
void f2(const char* s) { //old-style method. Legacy code we reuse
cout << s << '\n';
}
function<void()> make2(const string& s) {
return bind(f2, s.c_str()); //ups, bind copies pointer
}
int main() {
string s("abc");
function<void ()> g1 = make1(s);
function<void ()> g2 = make2(s);
s = "xyz";
g1(); //produces "abc"
g2(); //produces "xyz"
}
>
> Just to be clear, using char*s as strings is tricky and error prone -
> but that is a problem with C++, not a problem with boost.
> _______________________________________________
> 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