Boost logo

Boost Users :

Subject: Re: [Boost-users] [Bind] Unexpected behavior when binding constchar* to function
From: Eric Whitcombe (ericwsf_at_[hidden])
Date: 2010-04-27 14:26:40


----- Original Message -----
From: "Piotr Jachowicz" <pjachowi_at_[hidden]>
To: <boost-users_at_[hidden]>
Sent: Tuesday, April 27, 2010 1:53 PM
Subject: Re: [Boost-users] [Bind] Unexpected behavior when binding
constchar* to function

> 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".

Actually what you told bind to bind is an address of a buffer. So it did
exactly what you asked.
It is not really bind's fault that you changed the contents. If you pass a
mutatable object to anything
it isn't really fair to complain that it was mutated and that change
affected everthing that referenced that object.
Unless some special interface was designed to allow you to specify that you
want a copy made of the buffer it wouldn't be reasonable for the
implementation to assume it should do that. The buffer could be massive.
That kind of copying is what is specifically avoided intentionally by using
pointers.

...perhap boost::bind could try and determine the size of the buffer and
make an arbitrary decision on whether to copy or not but, that sounds even
worse.

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

I suspect because a temporary object is created, like any function that
takes a std::string receiving a char*.
I also suspect the same happens as a result of binding any fundemental type.
But when you use pointers ( to plain buffers or user-defined types)
you have to be responisble for the object's lifetime.

<snip>>> _______________________________________________


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